android - firebase:InstantiationException:无法实例化抽象类 java.util.TimeZone
问题描述
我尝试EventPojo
从这样的 firebase 数据库中解析 -classes 列表:
GenericTypeIndicator<HashMap<String, EventPojo>> tEvents = new GenericTypeIndicator<HashMap<String, EventPojo>>() {};
HashMap<String, EventPojo> events = dataSnapshot.child(getString(R.string.eventsNodeName)).getValue(tEvents);
在EventPojo
我有一个GregorianCalender
:
public class EventPojo implements Comparable<EventPojo>{
GregorianCalendar date;
...
当我尝试从数据库中获取 HashMap 时,我得到一个InstantiationException
:
java.lang.RuntimeException: java.lang.InstantiationException: Can't instantiate abstract class java.util.TimeZone
为什么firebase试图建立TimeZone
而不是GregorianCalender
?
解决方案
Firebase 实时数据库仅存储 JSON 类型。如果不编写自定义代码,就无法序列化/反序列化 a GregorianCalendar
(or )。TimeZone
我的典型方法是拥有一个 JSON 类型的属性(例如,Long
用于存储时间戳的 a),然后拥有一个返回应用程序使用的类型的 getter(GregorianCalendar
在您的情况下是 a)。为确保 Firebase 不会尝试序列化该GregorianCalendar
方法,请将其标记为@Exclude
(另请参阅:How to ignore new fields for an object model with Firebase 1.0.2,其中的一些示例)。
所以:
public class EventPojo implements Comparable<EventPojo>{
public Long timestamp
@Exclude
public GregorianCalendar getDate() {
...
}
@Exclude
public void getDate(GregorianCalendar date) {
...
}
...
有了这个,Firebase 将看到该timestamp
字段并从中读取并将其写入数据库,而您的代码仅与getDate()
和进行交互setDate()
。
推荐阅读
- c - 打印文本文件内容的函数
- python - 检查条件给出错误的结果
- arrays - 如果对象数组包含具有特定属性的对象,则 MongoDb 聚合 addField
- java - LINQ for java,过滤列表
- xslt-2.0 - XSLT 3.0 嵌套分组和计数字符串值
- python - 我可以知道为什么我不能将垂直值组合到水平值,而它一直给我生成值的最后一个值
- android - 没有足够的信息来推断类型变量 T
- java - 已解决 - 在 Eclipse 上将动态应用程序部署到 Tomcat 服务器后,Spring Web REST API 的 HTTP 状态 404
- php - 返回要在我的自定义仪表板中显示的用户成员身份 - SHORTCODE
- python - python中的for有什么用