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協程使用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: