Android kotlin+协程+Room数据库的简单使用

时间:2021-05-21

Room

Room是Google为了简化旧版的SQLite操作专门提供的
1.拥有了SQLite的所有操作功能
2.使用简单(类似于Retrofit),通过注解的方式实现相关功能。编译时自动生成实现类impl
3.LiveData,LifeCycle,Paging天然融合支持

导入

...plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-android-extensions' id 'kotlin-kapt'}dependencies { //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 协程操作库 //lifecycle implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'}

User

package com.zhangyu.myroom.dataimport android.os.Parcelableimport androidx.room.Entityimport androidx.room.PrimaryKeyimport kotlinx.android.parcel.Parcelize@Parcelize@Entity(tableName = "User")data class User( @PrimaryKey var id: String, var name: String) : Parcelable

UserDao

package com.zhangyu.myroom.dataimport androidx.room.*@Daointerface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun putUser(cacheBean: User) @Query("select * from User where id =:id") suspend fun getUser(id: String): User? @Query("select * from User") suspend fun getAllUser(): List<User>? @Delete fun delete(user: User) @Update(onConflict = OnConflictStrategy.REPLACE) fun update(user: User)}

UserDatabase

package com.zhangyu.myroom.dataimport android.util.Logimport androidx.room.Databaseimport androidx.room.Roomimport androidx.room.RoomDatabaseimport androidx.sqlite.db.SupportSQLiteDatabaseimport com.zhangyu.myroom.Appprivate const val TAG = "CacheDataBase"//后续的数据库升级是根据这个version来比较的,exportSchema导出架构@Database(entities = [User::class], version = 1, exportSchema = false)abstract class UserDatabase : RoomDatabase() { companion object { var dataBase: UserDatabase init { //如果databaseBuilder改为inMemoryDatabaseBuilder则创建一个内存数据库(进程销毁后,数据丢失) dataBase = Room.databaseBuilder(App.context, UserDatabase::class.java, "db_user") //是否允许在主线程进行查询 .allowMainThreadQueries() //数据库创建和打开后的回调,可以重写其中的方法 .addCallback(object : Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) Log.d(TAG, "onCreate: db_user") } }) //数据库升级异常之后的回滚 .fallbackToDestructiveMigration() .build() } } abstract fun getUserDao(): UserDao}

MainActivity

package com.zhangyu.myroomimport android.os.Bundleimport android.util.Logimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScopeimport com.zhangyu.myroom.data.Userimport com.zhangyu.myroom.data.UserDatabaseimport kotlinx.coroutines.launchprivate const val TAG = "MainActivity"class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) testCache() } private fun testCache() { val userDao = UserDatabase.dataBase.getUserDao() userDao.putUser(User("1001", "zhangyu")) userDao.putUser(User("1002", "liming")) lifecycleScope.launch { val users = userDao.getAllUser() Log.e(TAG, "users: $users") val user = userDao.getUser("1001") Log.e(TAG, "user: $user") Log.e(TAG, "testCache: 协程执行完毕") } Log.e(TAG, "testCache: ") }}

结果

E/MainActivity: testCache:
E/MainActivity: users: [User(id=1001, name=zhangyu), User(id=1002, name=liming)]
E/MainActivity: user: User(id=1001, name=zhangyu)
E/MainActivity: testCache: 协程执行完毕

到此这篇关于Android kotlin+协程+Room数据库的简单使用的文章就介绍到这了,更多相关Android kotlin协程使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章