Room Using Date field

我是研究僧i 提交于 2019-12-03 06:53:35

You're converting from Date to Long (wrapper) and from long (primitive) to Date. I changed it to Long and it compiled. Besides, unboxing null in your converter produces a NPE.

public class DateConverter {

    @TypeConverter
    public static Date toDate(Long dateLong){
        return dateLong == null ? null: new Date(dateLong);
    }

    @TypeConverter
    public static Long fromDate(Date date){
        return date == null ? null : date.getTime();
    }
}
Hassan Hallak

Put converter class in class of data base, not in the model :

@Database(entities = {
    Patient.class,Medicine.class,Tooth.class,})

@TypeConverters({TimeConverter.class,OutBoundConverter.class})

public abstract class PatientDataBase extends RoomDatabase {//your data base}
O95

I had this same problem (how to store time to Room), but I was using Calendar, so I made this: [note: This anwer is for Calendar]

  @TypeConverter
  public static Calendar toCalendar(Long l) {
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(l);
    return c;
  }

  @TypeConverter
  public static Long fromCalendar(Calendar c){
    return c == null ? null : c.getTime().getTime();
  }

See my complete example.

Refer to the documentation : https://developer.android.com/training/data-storage/room/referencing-data

public class Converters {
    @TypeConverter
    public static Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }
}

Then map it to the database.

@Database(entities = {User.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

And the entity.

@Entity
public class User {
    private Date birthday;
}

Using Calendar with Kotlin (adapted from O95's answer):

@TypeConverter
fun toCalendar(l: Long?): Calendar? =
    if (l == null) null else Calendar.getInstance().apply { timeInMillis = l }

@TypeConverter
fun fromCalendar(c: Calendar?): Long? = c?.time?.time
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!