Android Room-错误:无法弄清楚如何将该字段保存到数据库中 [英] Android Room - error: Cannot figure out how to save this field into database

查看:616
本文介绍了Android Room-错误:无法弄清楚如何将该字段保存到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

详细日志

error: Cannot figure out how to save this field into database. You can 
consider adding a type converter for it.
private final java.util.Date mTime = null;

我有一个实体,其字段为

I have an entity with a field as

var mStartTime : Date = Date() // java.util.Date

为什么房间"不能保留日期"对象?什么是Date的最佳转换器?

Why cant Room persist Date objects? What can be best converter for Date?

推荐答案

Date正是

例如,如果要保留Date的实例,可以编写以下TypeConverter来将等效的Unix时间戳存储在数据库中:

For example, if we want to persist instances of Date, we can write the following TypeConverter to store the equivalent Unix timestamp in the database:

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

前面的示例定义了2个函数,一个函数将Date对象转换为Long对象,另一个函数执行从Long到Date的逆转换.由于Room已经知道如何保留Long对象,因此可以使用此转换器保留Date类型的值.

The preceding example defines 2 functions, one that converts a Date object to a Long object and another that performs the inverse conversion, from Long to Date. Since Room already knows how to persist Long objects, it can use this converter to persist values of type Date.

接下来,您将@TypeConverters批注添加到AppDatabase类中,以便Room可以使用您为该AppDatabase中的每个实体和DAO定义的转换器:

Next, you add the @TypeConverters annotation to the AppDatabase class so that Room can use the converter that you've defined for each entity and DAO in that AppDatabase:

AppDatabase.java

AppDatabase.java

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

旁注:java.util.Date被认为设计不当(而java.util.Calendar更糟糕).如果您有任何不重要的日期时间逻辑,并且可以摆脱API级别26(台式机上的Java 8),通常最好使用 https://github.com/JakeWharton/ThreeTenABP 以获得反向移植.

A side note: java.util.Date is considered to be badly designed (and java.util.Calendar is much worse). If you have any non-trivial date-time logic and can get away with API level 26 (Java 8 on desktop), it's generally better to use java.time package. And if you can't, see https://github.com/JakeWharton/ThreeTenABP for a backport.

这篇关于Android Room-错误:无法弄清楚如何将该字段保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆