【发布时间】:2022-01-16 14:26:56
【问题描述】:
我没有收到任何错误,但在调试期间我的应用程序在此行崩溃:
currentWeatherDao.insertWeatherData(currentWeather)
在哪里
currentWeather = CurrentWeatherEntry(base=stations, clouds=Clouds(all=19), cod=200, coordinate=Coordinate(lat=50.0833, lon=19.9167), dt=1639359545, id=3094802, main=Main(feelsLike=-10.06, humidity=93, pressure=1023, temp=-4.69, tempMax=-0.63, tempMin=-6.89), name=Krakow, sys=Sys(country=PL, id=19912, message=0.0, sunrise=1639377067, sunset=1639406289, type=2), timezone=3600, visibility=2500, weather=[Weather(description=mist)], wind=Wind(deg=70, speed=4.02))
在我开始实施 TypeConverter 以在我的数据库中存储对象列表之前一切正常,现在应用程序在插入时崩溃,我找不到代码问题。
这里是相关代码。
实体:
const val CURRENT_WEATHER_ID = 0
@Entity(tableName = "current_weather")
data class CurrentWeatherEntry(
val base: String,
@Embedded(prefix = "clouds_")
val clouds: Clouds,
val cod: Int,
@SerializedName("coord")
@Embedded(prefix = "coordinate_")
val coordinate: Coordinate,
val dt: Int,
val id: Int,
@Embedded(prefix = "main_")
val main: Main,
val name: String,
@Embedded(prefix = "sys_")
val sys: Sys,
val timezone: Int,
val visibility: Int,
val weather: List<Weather>,
@Embedded(prefix = "wind_")
val wind: Wind
) {
@PrimaryKey(autoGenerate = false)
var keyId: Int = CURRENT_WEATHER_ID
constructor() :this("", Clouds(0), 0, Coordinate(0.0,0.0), 0, 0,
Main(0.0,0,0,0.0,0.0,0.0),
"",Sys("",0,0.0,0,0,0),0,
0, mutableListOf(Weather("")),Wind(0,0.0))
}
数据库:
@Database(
entities = [CurrentWeatherEntry::class],
version = 1
)
@TypeConverters(Converters::class)
abstract class ForecastDatabase: RoomDatabase() {
abstract fun getCurrentWeatherDao() : CurrentWeatherDao
companion object {
@Volatile private var instance: ForecastDatabase? = null
private val STOP = Any()
operator fun invoke(context: Context) = instance ?: synchronized(STOP){
instance ?: createDatabase(context).also{instance = it}
}
private fun createDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
ForecastDatabase::class.java, "forecast.db")
.build()
}
}
道:
@Dao
interface CurrentWeatherDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertWeatherData(weatherEntry:CurrentWeatherEntry)
@Query("select * from current_weather where keyId = $CURRENT_WEATHER_ID")
fun readWeatherData(): LiveData<CurrentWeatherEntry>
}
转换器:
class Converters {
@TypeConverter
fun fromListWeatherToString(weatherList: List<Weather>):String
{
return Gson().toJson(weatherList)
}
@TypeConverter
fun fromStringToWeatherList(weatherString: String):List<Weather>
{
val listType: Type = object : TypeToken<List<Weather>>() {}.type
return Gson().fromJson(weatherString,listType)
}
【问题讨论】:
-
在您的 Converters 类中使用 ArrayList 而不是 List。
-
尝试了 ArrayList 和 MutableList,应用在插入时仍然崩溃。
标签: android kotlin mvvm android-room