kotlin room本地数据库 +list储存

先导入相关依赖

    implementation 'com.google.code.gson:gson:2.6.2'
    //room数据库
    implementation "androidx.room:room-runtime:2.2.5"
    kapt "androidx.room:room-compiler:2.2.5" // Kotlin 使用 kapt
    implementation "androidx.room:room-ktx:2.2.5"//Coroutines support for Room 协程操作库
    androidTestImplementation 'androidx.room:room-testing:2.2.3'

    //lifecycle
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'

创建数据表类型

说明: 

@TypeConverters(InspectionConverter::class) 转换器,大概原理就是把 表中的list 转换成 String来储存

@Entity(tableName = "Student")  AppDataBase指向Student 

ColumnInfo 如果是多表的话, 这个别名用于区分(我自己这么理解的,不知道对不对)

@TypeConverters(InspectionConverter::class)
@Entity(tableName = "Student")
data class Inspection(
    @PrimaryKey(autoGenerate = true)
    var id: Int?,
    @ColumnInfo(name = "s_name")
    var name: String?,
    @ColumnInfo(name = "s_type")
    var time: String?,
    var urlList: List<String> ?
)

转换器

class InspectionConverter {
    @TypeConverter
    fun stringToObject(value: String): List<String> {
        val listType = object : TypeToken<List<String>>() {}.type
        return Gson().fromJson(value, listType)
    }

    @TypeConverter
    fun objectToString(list: List<Any>): String {
        val gson = Gson()
        return gson.toJson(list)
    }
}
AppDataBase
@Database(entities = [Inspection::class], version = 1 , exportSchema = false)
abstract class AppDataBase : RoomDatabase() {

    abstract fun getInspectionDao(): InspectionDao


    companion object {
        val instance = Single.sin
    }

    private object Single {
        val sin :AppDataBase= Room.databaseBuilder(
            BaseApplication.context,
            AppDataBase::class.java,
            "User.db"
        )
            .allowMainThreadQueries()
            .build()
    }

}

增删改查

@Dao
interface InspectionDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(element:Inspection)

    @Query("select * from Student")
    fun getAllInspections():MutableList<Inspection>

    @Query("select * from Student where id = :id")
    fun getInspection(id:Int):Inspection

    @Query("select * from Student order by id desc ")
    fun getAllByDateDesc():MutableList<Inspection>

    @Query("delete from Student where id = :id")
    fun delete(id:Int)

    @Query("delete from Student")
    fun deleteAll()

}

使用: 

 val inspectionDao :InspectionDao = AppDataBase.instance.getInspectionDao()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值