0

My TypeConverter is not working for converting GregorianCalendar to an sql Date type. An error is being thrown on the following code:

/** due date of item */
@TypeConverters({CalendarConverter.class})
private GregorianCalendar dueDate = null;

Error:(42, 31) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

The TypeConverter code:

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());
}

}

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161

1 Answers1

0

Room can only store simple data types, you need to provide a type converter for Date (or change your converter to convert Calender to 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();
    }
}

Or something like this:

 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();
}
Kackao
  • 1,181
  • 3
  • 13
  • 22