提问人:Murphler 提问时间:5/13/2021 最后编辑:user2340612Murphler 更新时间:5/14/2021 访问量:40
为什么我的 TypeConverter 没有被调用/使用。程序似乎无法识别它
Why isn't my TypeConverter being called / used. Program doesn't appear to recognise it
问:
我有一个链接到我的数据库的 TypeConverter 类,但它似乎没有被调用,因此我收到以下错误
ForecastAQSpecified.java:9: error: Cannot figure out how to read this field from a cursor.
private final java.time.LocalDate dt = null;
dt 是我在 JSON 响应中以 epoch Int 形式获得的日期时间。我希望将其转换为 LocalDate。My Entity 类如下所示
@Entity(tableName = "future_AQ", indices = [Index(value = ["dt"], unique = true)])
data class ForecastAQ(
@PrimaryKey(autoGenerate = true)
val id: Int? = null,
@Embedded
val components: Components,
val dt: Int,
@Embedded
val main: Main
)
val dt:Int 是我想要转换的内容。我的 TypeConverter 类如下
object DateConverter {
@TypeConverter
@JvmStatic
fun stringToDate(str: String?) = str?.let {
LocalDate.parse(it, DateTimeFormatter.ISO_LOCAL_DATE)
}
@TypeConverter
@JvmStatic
fun dateToString(localDate: LocalDate?) = localDate?.format(
DateTimeFormatter.ISO_LOCAL_DATE
)
@TypeConverter
@JvmStatic
fun timestampToDateTime(dt : Int?): LocalDate? {
try {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss")
val netDate = dt?.times(1000L)?.let { Date(it) }
val sdf2 = sdf.format(netDate)
return LocalDate.parse(sdf2, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
Log.d("TAG", "date " + LocalDate.parse(sdf2, DateTimeFormatter.ISO_LOCAL_DATE_TIME).toString());
} catch (e : Exception) {
return null
e.printStackTrace()
}
}
前两个在数据库的另一部分是必需的,我在其中以 String 形式接收日期响应。他们被召唤得很好。然而,我的最后一个不是 - 这是我需要将 Int 转换为 DateTime 对象的那个
数据库类如下,供参考
@Database(
entities = [CurrentConditions::class, ConditionsLocation::class, ForecastWeather::class, ForecastAQ::class],
version = 1
)
@TypeConverters(DateConverter::class)
abstract class ConditionsDatabase : RoomDatabase() {
abstract fun getCurrentConditionsDAO() : CurrentConditionsDAO
abstract fun getConditionsLocationDAO() : ConditionsLocationDAO
abstract fun getForecastWeatherDAO() : ForecastWeatherDAO
abstract fun getForecastAirQualDAO() : ForecastAqDAO
companion object{
@Volatile private var instance: ConditionsDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: buildDatabase(context).also {
instance = it
}
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
ConditionsDatabase::class.java, CURRENT_CONDITIONS_DATABASE_NAME)
.build()
}
}
非常感谢
答:
0赞
Maxim Tulupov
5/14/2021
#1
您应该创建一个类而不是对象
取代
object DateConverter {
自
class DateConverter {
删除 JvmStatic 注解
评论