会议室使用日期字段 [英] Room Using Date field
问题描述
我正在使用日期转换器类来转换我的日期对象。但是,我仍然遇到一个错误的说法。错误:无法弄清楚如何将该字段保存到数据库中。您可以考虑为其添加类型转换器。
I am using date converter class to convert my date object. However, I still encounter an error saying. error: Cannot figure out how to save this field into a database. You can consider adding a type converter for it.
我的日期转换器类
public class DateConverter {
@TypeConverter
public static Date toDate(Long dateLong){
return dateLong == null ? null: new Date(dateLong);
}
@TypeConverter
public static long fromDate(Date date){
return date == null ? null :date.getTime();
}
}
我的数据库表中使用日期对象。
@Entity(tableName = "userFitnessDailyRecords")
@TypeConverters(DateConverter.class)
public class UserFitnessDailyRecords {
@NonNull
@PrimaryKey(autoGenerate = true)
public int id;
public Date forDay;
public Date getForDay() {
return forDay;
}
public void setForDay(Date forDay) {
this.forDay = forDay;
}
}
我遵循了Google代码持久性实验室和commonwares室各自的GitHub示例。我正在使用1.0.0版的会议室。
I followed the example from google code persistence labs and from commonwares room respective GitHub example. I am using room version 1.0.0.
推荐答案
您正在从Date转换为 Long (包装器),并从 long (原始)至今。我将其更改为Long并进行了编译。
You're converting from Date to Long (wrapper) and from long (primitive) to Date. I changed it to Long and it compiled. Besides, unboxing null in your converter produces a NPE.
public class DateConverter {
@TypeConverter
public static Date toDate(Long dateLong){
return dateLong == null ? null: new Date(dateLong);
}
@TypeConverter
public static Long fromDate(Date date){
return date == null ? null : date.getTime();
}
}
这篇关于会议室使用日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!