Search code examples
androidandroid-roomandroid-databaseandroid-date

Room Using Date field


I am using date converter class to convert my date object. However, I still encounter an error saying. error: Cannot figure out how to save this field into a database. You can consider adding a type converter for it.

My Date Converter class

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

My Database table for using the date object.

@Entity(tableName = "userFitnessDailyRecords")

    @TypeConverters(DateConverter.class)
    public class UserFitnessDailyRecords {

        @NonNull
        @PrimaryKey(autoGenerate = true)
        public int id;
        public Date forDay;

        public Date getForDay() {
            return forDay;
        }

        public void setForDay(Date forDay) {
            this.forDay = forDay;
        }
    }

I followed the example from google code persistence labs and from commonwares room respective GitHub example. I am using room version 1.0.0.


Solution

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