详细日志(log)

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;

我有一个实体,其字段为

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

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

推荐答案

Date正是https://developer.android.com/training/data-storage/room/referencing-data中给出的例子.

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

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定义的转换器:

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),通常最好使用java.time package.如果不能,请参阅https://github.com/JakeWharton/ThreeTenABP了解后端口.

Kotlin相关问答推荐

Lambda和普通Kotlin函数有什么区别?

如何在Kotlin中反射多个对象以查找特定类型的属性

在Kotlin中求n个ClosedRange实例相交的最常用方法是什么?

Kotlin:将泛型添加到列表任何>

可以从背景图像中点击图标吗?

用Quarkus和Reactor重写异步过滤器中的数据流

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

第二个协程永远不会执行

在 Kotlin 协程中切换 IO 和 UI 的正确方法是什么?

通过顺序多米诺骨牌操作列表管理对象的最佳方法是什么?

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

在 Kotlin 中使用 @Parcelize 注释时如何忽略字段

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

如何退出 Kotlinc 命令行编译器

在 Spring Framework 5.1 中注册具有相同名称的测试 bean

如何将命令行参数传递给Gradle Kotlin DSL

如何在Kotlin中获得KType?

在 Kotlin 中创建非绑定服务

如何根据ArrayList的对象属性值从中获取最小/最大值?

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?