gpt4 book ai didi

java - Android 房间 - 错误 : Cannot figure out how to save this field into database

转载 作者:IT老高 更新时间:2023-10-28 13:44:04 25 4
gpt4 key购买 nike

详细日志

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

为什么 Room 不能保留 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.

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

@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用于反向移植。

关于java - Android 房间 - 错误 : Cannot figure out how to save this field into database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50515820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com