Android jetpack actual room

Time:2021-12-2

Android jetpack actual room

Then the last article said that we know the room database and the basic usage, so how can we use it conveniently in practice?
How to rely on, please watchLast
—————————————–Get to work——————————————
For example, when we cache the user’s basic data, I want to put the avatar. Nicknames and other data that you want to cache can be cached and saved locally.
Similarly, we need to create an entity class or a table called userentity

@Entity
class UserEntity {

    @PrimaryKey
    Lateinit var userid: string // primary key ID

    var userName:String?=null

    var password:String?=null

    var imgurl:String?=null

    var age:Int?=0

    var sex:String?=null

    var phone:String?=null
}

We can also customize other table names: in the @ entity annotation, we passed in a parameter tablename to specify the name of the table @ entity (tablename = “users”)
With a watch, what do we need to do next? Of course, we need to query the table. Let’s create a userdao query class

@Dao
interface UserDao {
    //Query table data
    @WorkerThread
    @Query("SELECT * FROM  UserEntity ")
    fun getUser(): UserEntity?

    //Query entire table list data
    @WorkerThread
    @Query("SELECT * FROM UserEntity")
    fun getUserAll(): LiveData<UserEntity>

    //Insert data
    @WorkerThread
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(userEntity: UserEntity)

    //Modify table contents
    @WorkerThread
    @Update
    fun update(userEntity: UserEntity)
    
    //Modify table array contents
    @WorkerThread
    @Update
    fun update(userEntity: List<UserEntity>)
    //Delete table
    @WorkerThread
    @Query("DELETE FROM UserEntity")
    fun deleteAll()
}

-The above is the query class. It’s OK to write the query statement according to your own needs. Then someone asked what livedata is, and weNextLet’s explain the functions and usage scenarios of this class in detail. Next, we will also initialize, query and insert data. We define an abstract dbdatabase class, inherit roomdatabase and add the annotation @ database to identify it

@Database(entities = [UserEntity::class],
version = 1,
exportSchema = true)
abstract class DBDataBase:RoomDatabase() {
    companion object{
       //app_ Database is the database name
        fun getDataBase(context: Context): DBDataBase {
            return Room.databaseBuilder(context.applicationContext,DBDataBase::class.java,"app_database.db")
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_1_to_2)
                .build()
        }
        private val MIGRATION_1_to_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {

            }
        }
    }
    abstract fun UserDao(): UserDao
}

Database upgrade and downgrade

When using a database, you can’t avoid updating the database. To upgrade or demote a database, use the addmigrations method:

fun getDataBase(context: Context): DBDataBase {
            return Room.databaseBuilder(context.applicationContext,DBDataBase::class.java,name)
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_1_to_2)
                .build()
        }
        private val MIGRATION_1_to_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {

            }
        }
    }

Migration requires two parameters. Startversion indicates the version to which the upgrade starts, and endversion indicates the version to which the upgrade is to be made. At the same time, you need to modify the value of version in the @ database annotation to be the same as endversion.
The same is true for database degradation. Addmigrations is also used, only startversion > endversion.

When the version does not match during upgrade or downgrade, exceptions will be thrown directly by default. Of course, we can also handle exceptions.

When upgrading, you can add the fallbacktodestructivemigration method. When the version does not match, the table will be directly deleted and recreated.

When demoting, add the fallbacktodestructivemigrationondowngrade method. When the version does not match, the table will be directly deleted and recreated.

We start to use it and create a datarepository. When we use rxjava retro fit, we will have an interface to use the help class. This datarepository can be handled by ourselves according to personal writing and encapsulation

class DataRepository() {
    private lateinit var dbDataBase: DBDataBase
    private lateinit var application: Application
    constructor(application: Application, dbbase: DBDataBase) : this(){
        this.application=application
        this.dbDataBase=dbbase
    }

    //Insert data
    fun insert(entity:UserEntity){
        dbDataBase.UserDao().insert(entity)

    }

We initialize database and datarepository in application

class App : Application() {
    private lateinit var dbDataBase: DBDataBase
    private lateinit var mDataRepository: DataRepository
    override fun onCreate() {
        super.onCreate()
        dbDataBase =DBDataBase.getDataBase(this)
        mDataRepository =DataRepository(this, dbDataBase)
    }

    fun getRepository() = mDataRepository
}

use

We can use it in the activity

   fun getRepository(): DataRepository {
        return (application as App).getRepository()
    }

insert data

private fun onInsert() {
        val userEntity = UserEntity()
        userEntity.age = 18
        userEntity.imgurl = "url"
        userEntity.password = "123456"
        Userentity.username = "Zhang Shan"
        Userentity.sex = "female"
        userEntity.phone = "1560000xxxx"
        userEntity.userId = "1"
        getRepository().insert(userEntity)
    }

get data

 private fun onObtain() {
        getRepository().getUser().observe(this, Observer {
            Log.d(TAG, it.password ?: "")
     

Modify data

private fun onUpdate() {
        val userEntity = UserEntity()
        userEntity.age = 17
        userEntity.imgurl = "url"
        userEntity.password = "123456"
        Userentity.username = "Zhang Shan"
        Userentity.sex = "female"
        userEntity.phone = "1560000xxxx"
        userEntity.userId = "1"
        getRepository().update(userEntity)
    }

Insert, modify and obtain all codes

class MainActivity : AppCompatActivity() {
    private val mBing by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val TAG: String = MainActivity::class.java.simpleName
    fun getRepository(): DataRepository {
        return (application as App).getRepository()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBing.root)
        mBing.tvInsert.setOnClickListener {
            onInsert()
        }
        mBing.tvSelect.setOnClickListener {
            onObtain()
        }

    }

    private fun onInsert() {
        val userEntity = UserEntity()
        userEntity.age = 18
        userEntity.imgurl = "url"
        userEntity.password = "123456"
        Userentity.username = "Zhang Shan"
        Userentity.sex = "female"
        userEntity.phone = "1560000xxxx"
        userEntity.userId = "1"
        getRepository().insert(userEntity)
    }
    private fun onUpdate() {
        val userEntity = UserEntity()
        userEntity.age = 17
        userEntity.imgurl = "url"
        userEntity.password = "123456"
        Userentity.username = "Zhang Shan"
        Userentity.sex = "female"
        userEntity.phone = "1560000xxxx"
        userEntity.userId = "1"
        getRepository().update(userEntity)
    }

    private fun onObtain() {
        getRepository().getUser().observe(this, Observer {
            Log.d(TAG, it.password ?: "")
        })
    }
}
Android jetpack actual room

image.png