我的TypeConverter无法将GregorianCalendar转换为sql Date类型。以下代码引发错误:
/** due date of item */
@TypeConverters({CalendarConverter.class})
private GregorianCalendar dueDate = null;
错误:(42,31)错误:无法弄清楚如何将此字段保存到数据库中。你可以考虑为它添加一个类型转换器。
TypeConverter代码:
public class CalendarConverter {
@TypeConverter
public static GregorianCalendar fromDate(Date value){
if(value == null){
throw new NullPointerException("must not be null");
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(value);
return cal;
}
@TypeConverter
public static Date toDate(GregorianCalendar calendar){
if(calendar != null){
throw new NullPointerException("must not be null");
}
Calendar cal = calendar;
return new Date(cal.getTime().getTime());
}
}
答案 0 :(得分:0)
Room只能存储简单数据类型,您需要为Date提供类型转换器(或更改转换器以将Calender转换为Long):
@TypeConverter
public Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public Long dateToTimestamp(Date date) {
if (date == null) {
return null;
} else {
return date.getTime();
}
}
或类似的东西:
public class CalendarConverter {
@TypeConverter
public static GregorianCalendar fromLong(Long value){
if(value == null){
throw new NullPointerException("must not be null");
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date(value));
return cal;
}
@TypeConverter
public static Long toLong(GregorianCalendar calendar){
if(calendar != null){
throw new NullPointerException("must not be null");
}
Calendar cal = calendar;
return cal.getTime();
}