Simple Use of Android kotlin + Synergetic + Room Database
- 2021-12-11 09:02:29
- OfStack
Room
Room is specially provided by Google to simplify the operation of the older version of SQLite
1. Have all the operation functions of SQLite
2. It is easy to use (similar to Retrofit), and related functions are realized by annotation. Automatically generate the implementation class impl at compile time
3. Natural fusion support of LiveData, LifeCycle and Paging
Import
...
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
id 'kotlin-kapt'
}
dependencies {
//room Database
implementation "androidx.room:room-runtime:2.2.5"
kapt "androidx.room:room-compiler:2.2.5" // Kotlin Use kapt
implementation "androidx.room:room-ktx:2.2.5"//Coroutines support for Room Synergetic operation library
//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"
// Subsequent database upgrades are based on this version To compare, exportSchema Export schema
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
companion object {
var dataBase: UserDatabase
init {
// If databaseBuilder Replace with inMemoryDatabaseBuilder Is created 1 Main memory database (data lost after process destruction)
dataBase = Room.databaseBuilder(App.context, UserDatabase::class.java, "db_user")
// Whether to allow queries on the main thread
.allowMainThreadQueries()
// Callbacks after the database is created and opened, which can override the methods in it
.addCallback(object : Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
Log.d(TAG, "onCreate: db_user")
}
})
// Rollback after database upgrade exception
.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: Complete the execution of the coordination process ")
}
Log.e(TAG, "testCache: ")
}
}
Results
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: Co-execution completed