Room Using Date field
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(); }}
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.
@Entitypublic class User { private Date birthday;}
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 ; the main reason is that Calendar is now supported]
edit: the main reason for this answer is that Date
is deprecated, so here you go
@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(); }