Q1 ViewModel需要Context
使用AndroidViewModel,初始化与ViewModel有点不同
ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(NoticeViewModel::class.java)
注意是ViewModelProvider.AndroidViewModelFactory而不是ViewModelProvider.NewInstanceFactory
Q2 LiveData与Room
要达到Room修改能实时刷新界面,必须得在同一个实例下进行操作
val user1 = User(null,"大虎")
val user2 = User(null,"二郎")
val user3 = User(null,"三师兄")
GlobalScope.launch(Dispatchers.IO){
userDao.addUser(user1,user2,user3)
val all = userDao.getAll()
withContext(Dispatchers.Main){
all.observe(this@MainActivity, Observer {
it.forEach { user-> Log.d(TAG, "LiveData+Room: id = ${user.id} name = ${user.name}") }
})
Log.d(TAG, "onCreate: 1111111111111111")
}
delay(2000)
Log.d(TAG, "onCreate: 分割线--------------------------------")
userDao.addUser(User(null,"我是验证LiveData的"))
delay(2000)
Log.d(TAG, "onCreate: 分割线--------------------------------")
userDao1.delUser()
delay(2000)
Log.d(TAG, "onCreate: 分割线--------------------------------")
userDao2.updateUser(User(1,"李四"))
}
2020-07-08 16:28:57.236 13991-13991/com.liuzhi.myapp D/MainActivity: LiveData+Room: id = 1 name = 大虎
2020-07-08 16:28:57.236 13991-13991/com.liuzhi.myapp D/MainActivity: LiveData+Room: id = 2 name = 二郎
2020-07-08 16:28:57.236 13991-13991/com.liuzhi.myapp D/MainActivity: LiveData+Room: id = 3 name = 三师兄
2020-07-08 16:28:59.227 13991-14059/com.liuzhi.myapp D/MainActivity: onCreate: 分割线--------------------------------
2020-07-08 16:28:59.251 13991-13991/com.liuzhi.myapp D/MainActivity: LiveData+Room: id = 1 name = 大虎
2020-07-08 16:28:59.251 13991-13991/com.liuzhi.myapp D/MainActivity: LiveData+Room: id = 2 name = 二郎
2020-07-08 16:28:59.251 13991-13991/com.liuzhi.myapp D/MainActivity: LiveData+Room: id = 3 name = 三师兄
2020-07-08 16:28:59.251 13991-13991/com.liuzhi.myapp D/MainActivity: LiveData+Room: id = 4 name = 我是验证LiveData的
2020-07-08 16:29:01.231 13991-14164/com.liuzhi.myapp D/MainActivity: onCreate: 分割线--------------------------------
2020-07-08 16:29:03.258 13991-14164/com.liuzhi.myapp D/MainActivity: onCreate: 分割线--------------------------------
Q3 Room的数据库连接实例创建
自己在网上搜Kotlin实例创建方法,发现各种高深,完全看不懂,特别是by lazy这种(自己学艺不精),最后只能用Studio自带的Java to Kotlin 转换插件,发现代码差不多
companion object{
private var databaseInstance : RoomDatabase? = null
fun getDatabase(application: Application) : RoomDatabase?{
if(databaseInstance == null){
synchronized(RoomDatabase::class.java){
if(databaseInstance == null){
databaseInstance = Room.databaseBuilder(
application,
RoomDatabase::class.java,
"database.db"
).build()
}
}
}
return databaseInstance
}
网友评论