我正在尝试将日历转换为long,以便使用空间添加到数据库中。
我以为我的代码可以用,但是好像失败了。
@Entity(tableName = "reminders")
public class Reminder {
@PrimaryKey(autoGenerate = true)
private int rid;
private String name;
private String note;
@TypeConverters({CalendarConverter.class})
private Calendar calendar;
private int priority;
private boolean enabled;
public Reminder(String name, String note, String date, int priority, int enabled) {
this.name = name;
this.note = note;
this.priority = priority;
if (enabled == 0)
this.enabled = false;
else
this.enabled = true;
String[] dateSplit = date.split("/");
int day = Integer.parseInt(dateSplit[0]);
int month = Integer.parseInt(dateSplit[1]);
int year = Integer.parseInt(dateSplit[2]);
calendar = new GregorianCalendar(year, month - 1, day);
}
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.getTimeInMillis();
}
}
我找不到尝试将日历转换为long时犯的错误。
错误:“无法弄清楚如何将该字段保存到数据库中。您可以考虑为其添加类型转换器。”