1.room数据库结构
2.添加依赖:
implementation'androidx.lifecycle:lifecycle-livedata-ktx:2.3.0'
implementation'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0'
implementation'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation"androidx.activity:activity-ktx:1.2.0-beta01"
implementation'com.kunminx.archi:unpeek-livedata:4.5.0-beta1'
def room_version ="2.3.0"
implementation"androidx.room:room-runtime:$room_version"
implementation"androidx.room:room-ktx:$room_version"
kapt"androidx.room:room-compiler:$room_version"
3.构建项目
@Entity
data class Record(
@PrimaryKey(autoGenerate = true)//表主键 ,autoGenerate = true 自增
val id: Long = 0,
@ColumnInfo(name = "title")
val title: String,
@ColumnInfo(name = "content")
val content: String,
/**
* Room会利用@Entity注解的类的所有字段来创建表的列,
* 如果某些字段不希望存储的话,使用@Ignore注解该字段即可
*/
@Ignore
val bitmap: Bitmap?
)
@Dao
interface RecordDao {
@Query("select * from record where title = :title")
fun getAllRecordsByTitle(title: String): Flow<List<Record>>
@Query("select * from record")
fun getAllRecords(): Flow<List<Record>>
@Insert
suspend fun insert(vararg record: Record?)
@Update
fun update(vararg record: Record?)
@Delete
fun delete(vararg record: Record?)
}
//每次创建AppDatabase实例都会产生比较大的开销,所以应该将AppDatabase设计成单例的
@Database(
entities = [Record::class],
version = 2,
exportSchema = false
)
abstract class AppDataBase : RoomDatabase() {
abstract fun recordDao(): RecordDao
companion object {
private var instance: AppDataBase? = null
// 使用单例模式
fun getDatabase(context: Context): AppDataBase {
return instance?: synchronized(this){
Room.databaseBuilder(
context.applicationContext,
AppDataBase::class.java, "app_database"
).build().also { instance = it }
}
}
}
}
class HomeViewModel(app: Application) : AndroidViewModel(app) {
private val recordDao by lazy {
AppDataBase.getDatabase(getApplication()).recordDao()
}
fun getAllRecord(){
viewModelScope.launch {
recordDao.getAllRecords().collect {
Log.e("TAG", "getAllRecord: $it", )
}
}
}
fun addRecord(title:String,content:String){
viewModelScope.launch {
recordDao.insert(Record(0,title,content))
}
}
}
class MainActivity : AppCompatActivity() {
private lateinit var mBinding: ActivityMainBinding
private val vm by viewModels<HomeViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
mBinding.btnAdd.setOnClickListener {
vm.addRecord(mBinding.etTitle.text.toString(),mBinding.etContent.text.toString())
}
mBinding.btnFind.setOnClickListener {
vm.getAllRecord()
}
}
}
4.room数据库与liveData和flow无缝连接,直接使用