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"//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.data

import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize

@Parcelize
@Entity(tableName = "User")
data class User(
  @PrimaryKey
  var id: String,
  var name: String
) : Parcelable

UserDao

package com.zhangyu.myroom.data

import androidx.room.*

@Dao
interface 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.data

import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.zhangyu.myroom.App

private 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.myroom

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.zhangyu.myroom.data.User
import com.zhangyu.myroom.data.UserDatabase
import kotlinx.coroutines.launch

private 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协程使用内容请搜索鸟哥教程(niaoge.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持鸟哥教程(niaoge.com)!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。