【问题标题】:GregorianCalendar field not being converted to Date through TypeConverterGregorianCalendar 字段未通过 TypeConverter 转换为 Date
【发布时间】: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());
}

}

【问题讨论】:

    标签: java android-studio android-room date-conversion java.util.calendar


    【解决方案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();
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-19
      • 1970-01-01
      • 2021-08-30
      • 2013-03-02
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多