先导入相关依赖
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()