Android kotlin+协程+Room数据库的简单使用
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"//CoroutinessupportforRoom协程操作库 //lifecycle implementation'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0' }
User
packagecom.zhangyu.myroom.data importandroid.os.Parcelable importandroidx.room.Entity importandroidx.room.PrimaryKey importkotlinx.android.parcel.Parcelize @Parcelize @Entity(tableName="User") dataclassUser( @PrimaryKey varid:String, varname:String ):Parcelable
UserDao
packagecom.zhangyu.myroom.data importandroidx.room.* @Dao interfaceUserDao{ @Insert(onConflict=OnConflictStrategy.REPLACE) funputUser(cacheBean:User) @Query("select*fromUserwhereid=:id") suspendfungetUser(id:String):User? @Query("select*fromUser") suspendfungetAllUser():List? @Delete fundelete(user:User) @Update(onConflict=OnConflictStrategy.REPLACE) funupdate(user:User) }
UserDatabase
packagecom.zhangyu.myroom.data importandroid.util.Log importandroidx.room.Database importandroidx.room.Room importandroidx.room.RoomDatabase importandroidx.sqlite.db.SupportSQLiteDatabase importcom.zhangyu.myroom.App privateconstvalTAG="CacheDataBase" //后续的数据库升级是根据这个version来比较的,exportSchema导出架构 @Database(entities=[User::class],version=1,exportSchema=false) abstractclassUserDatabase:RoomDatabase(){ companionobject{ vardataBase:UserDatabase init{ //如果databaseBuilder改为inMemoryDatabaseBuilder则创建一个内存数据库(进程销毁后,数据丢失) dataBase=Room.databaseBuilder(App.context,UserDatabase::class.java,"db_user") //是否允许在主线程进行查询 .allowMainThreadQueries() //数据库创建和打开后的回调,可以重写其中的方法 .addCallback(object:Callback(){ overridefunonCreate(db:SupportSQLiteDatabase){ super.onCreate(db) Log.d(TAG,"onCreate:db_user") } }) //数据库升级异常之后的回滚 .fallbackToDestructiveMigration() .build() } } abstractfungetUserDao():UserDao }
MainActivity
packagecom.zhangyu.myroom importandroid.os.Bundle importandroid.util.Log importandroidx.appcompat.app.AppCompatActivity importandroidx.lifecycle.lifecycleScope importcom.zhangyu.myroom.data.User importcom.zhangyu.myroom.data.UserDatabase importkotlinx.coroutines.launch privateconstvalTAG="MainActivity" classMainActivity:AppCompatActivity(){ overridefunonCreate(savedInstanceState:Bundle?){ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) testCache() } privatefuntestCache(){ valuserDao=UserDatabase.dataBase.getUserDao() userDao.putUser(User("1001","zhangyu")) userDao.putUser(User("1002","liming")) lifecycleScope.launch{ valusers=userDao.getAllUser() Log.e(TAG,"users:$users") valuser=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:协程执行完毕
到此这篇关于Androidkotlin+协程+Room数据库的简单使用的文章就介绍到这了,更多相关Androidkotlin协程使用内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!