记录一下room数据库的集成使用
1. 集成
implementation "androidx.room:room-runtime:2.4.2"
kapt "androidx.room:room-compiler:2.4.2"
implementation "androidx.room:room-ktx:2.4.2"
2. 创建数据对象
@Entity ( tableName= "draft_table" )
@Parcelize
data class DraftModel (
@PrimaryKey ( autoGenerate= true )
var id: Long = System. currentTimeMillis ( ) ,
var imageUrl: String,
var dataTime: String,
@TypeConverters ( Converters:: class )
var imagesList: ArrayList< String>
) : Parcelable
3. 实现数据库api接口
@Dao
interface DraftDao {
@Insert ( onConflict = OnConflictStrategy. REPLACE)
fun insertDraft ( draft: DraftModel)
@Query ( "SELECT * FROM draft_table" )
fun getAllDrafts ( ) : List< DraftModel>
@Query ( "DELETE FROM draft_table WHERE id = :Id" )
fun deleteUserById ( Id: Long)
}
4. 创建数据库
@TypeConverters ( Converters:: class )
@Database ( entities = [ DraftModel:: class ] , version = 1 , exportSchema = false )
abstract class DraftDatabase : RoomDatabase ( ) {
abstract fun draftDao ( ) : DraftDao
companion object {
private var database: DraftDatabase? = null
fun db ( ) : DraftDatabase {
if ( database != null ) return database!!
synchronized ( this ) {
if ( database == null ) {
database = Room. databaseBuilder (
Utils. getApp ( ) . applicationContext!! ,
DraftDatabase:: class . java,
"picture.db"
) . build ( )
}
}
return database!!
}
}
}
5. 类型转换器实现可能需要
class Converters {
@TypeConverter
fun fromArrayListToString ( list: ArrayList< String> ) : String {
return Gson ( ) . toJson ( list)
}
@TypeConverter
fun fromStringToArrayList ( data : String) : ArrayList< String> {
val listType = object : TypeToken< ArrayList< String> > ( ) { } . type
return Gson ( ) . fromJson ( data , listType)
}
}
6. 数据库使用
val draft = DraftModel ( imageUrl = imageUrl, imagesList = imagesList, dataTime = dataTime)
GlobalScope. launch ( Dispatchers. IO) {
dao. insertDraft ( draft)
}