当前位置:网站首页>Map structure stored in the room of jetpack series

Map structure stored in the room of jetpack series

2022-07-23 14:53:00 When it rains at night in Bashan

cause

Recently, I made a demand , Need to put the equipment ( You can't connect to the Internet ) Data of middle buried point , It is transmitted to App, then App Then upload to the buried point platform , My plan is , Store every buried point in the database , then App When selecting a machine to read , The device reads the database and returns json strand ,App After receiving the data , Conduct SDK Buried point .

work

Build table , Event name , Parameters , Time stamp , So the entity classes are as follows :

@Entity(tableName = "app_point_log")
data class AppPointLogEntity(
  var eventName: String,
  var eventParams: Map<String, String>,
  var timeStamp: Long
) {
    
  @PrimaryKey(autoGenerate = true)
  @ColumnInfo(name = "id")
  var id: Long = 0
}

Then write DAO as well as Repository layer , I won't repeat it here . After writing , Manually click compile , An error is as follows :

 error : Cannot figure out how to save this field into database. You can consider adding a type converter for it. - eventParams in com.xxxx.libdomain.data.point.AppPointLogEntity
 error : Cannot figure out how to read this field from a cursor. - eventParams in com.xxxx.libdomain.data.point.AppPointLogEntity

Is the meaning clear enough , It is suggested to add a converter
This Converter as follows :

class MapTypeConverter {
    

    @TypeConverter
    fun stringToMap(value: String): Map<String, String> {
    
        return Gson().fromJson(value, object : TypeToken<Map<String, String>>() {
    }.type)
    }
    @TypeConverter
    fun mapToString(value: Map<String, String>?): String {
    
        return if (value == null) "" else Gson().toJson(value)
    }
}

After you've written , You must remember , Add it to this place

@Database(entities = [AppPointLogEntity::class], version = 1, exportSchema = false)
@TypeConverters(MapTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
    
   abstract fun appPointLogDao(): AppPointLogDao
}

Compile again , No longer an error , Get it done !!!

原网站

版权声明
本文为[When it rains at night in Bashan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230925400614.html