GregorianCalendar 字段未通过 TypeConverter 转换为 Date
Posted
技术标签:
【中文标题】GregorianCalendar 字段未通过 TypeConverter 转换为 Date【英文标题】:GregorianCalendar field not being converted to Date through TypeConverter 【发布时间】:2018-08-14 14:51:13 【问题描述】:我的 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());
【问题讨论】:
【参考方案1】: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();
【讨论】:
以上是关于GregorianCalendar 字段未通过 TypeConverter 转换为 Date的主要内容,如果未能解决你的问题,请参考以下文章