Android之JetPack实战Room
接着上篇文章说,我们认识了room数据库,也知道基本用法,那么在实战中我们如何方便的去使用它呢?
如何依赖请观看上一篇
----------------------------------------- 开始干活------------------------------------------
比如我们在缓存用户基本资料数据时候,我要把头像。昵称等缓存一下,或者其他想要缓存的数据都可以缓存下来进行本地保存。
同样我们例外需要创建一个实体类或者叫创建一个表叫UserEntity
@Entity
class UserEntity {
@PrimaryKey
lateinit var userId:String //主键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
}
我们也可以自定义其他表名:在@Entity注解中我们传入了一个参数tableName用来指定表的名称@Entity(tableName = "users")
有了表之后我们接下来需要做什么呢?当然需要去查询表了,那我们创建一个UserDao的查询类
@Dao
interface UserDao {
//查询表数据
@WorkerThread
@Query("SELECT * FROM UserEntity ")
fun getUser(): UserEntity?
//查询整个表列表数据
@WorkerThread
@Query("SELECT * FROM UserEntity")
fun getUserAll(): LiveData<UserEntity>
//插入数据
@WorkerThread
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(userEntity: UserEntity)
//修改表内容
@WorkerThread
@Update
fun update(userEntity: UserEntity)
//修改表数组内容
@WorkerThread
@Update
fun update(userEntity: List<UserEntity>)
//删除表
@WorkerThread
@Query("DELETE FROM UserEntity")
fun deleteAll()
}
-以上就是查询类,查询语句根据自己需求去写就OK了,那么有人问LiveData这个是什么,这个我们下一篇我们来详细讲解这个类的作用与使用场景,接下来我们还要初始化和数据查询与插入等。我们定义一个抽象DBDataBase类,继承RoomDatabase并添加注解 @Database 来标识
@Database(entities = [UserEntity::class],
version = 1,
exportSchema = true)
abstract class DBDataBase:RoomDatabase() {
companion object{
//app_database为数据库名称
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
}
数据库升级与降级
在使用数据库的时候避免不了的就是数据库的更新。数据库的升级或者降级使用addMigrations方法进行操作:
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需要两个参数,startVersion表示的是升级开始的版本,endVersion表示要升级到的版本。同时需要将@Database注解中的version的值修改为和endVersion相同。
数据库降级使用也是一样。也是使用addMigrations只是startVersion > endVersion 。
当在升级或者降级的过程中出现版本未匹配到的情况的时候,默认情况下会直接抛异常出来。当然我们也可以处理异常。
升级的时候可以添加fallbackToDestructiveMigration方法,当未匹配到版本的时候就会直接删除表然后重新创建。
降级的时候添加fallbackToDestructiveMigrationOnDowngrade方法,当未匹配到版本的时候就会直接删除表然后重新创建。
我们开始使用,创建一个DataRepository,这个类我们在使用Rxjava Retrofit会有一个接口使用帮助类,这个DataRepository就可以,具体根据个人写法与封装自行处理
class DataRepository() {
private lateinit var dbDataBase: DBDataBase
private lateinit var application: Application
constructor(application: Application, dbbase: DBDataBase) : this(){
this.application=application
this.dbDataBase=dbbase
}
//插入数据
fun insert(entity:UserEntity){
dbDataBase.UserDao().insert(entity)
}
我们在Application中初始化database与DataRepository
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
}
使用
我们在Activity的时候可以在里面使用
fun getRepository(): DataRepository {
return (application as App).getRepository()
}
插入数据
private fun onInsert() {
val userEntity = UserEntity()
userEntity.age = 18
userEntity.imgurl = "url"
userEntity.password = "123456"
userEntity.userName = "张珊"
userEntity.sex = "女"
userEntity.phone = "1560000xxxx"
userEntity.userId = "1"
getRepository().insert(userEntity)
}
获取数据
private fun onObtain() {
getRepository().getUser().observe(this, Observer {
Log.d(TAG, it.password ?: "")
修改数据
private fun onUpdate() {
val userEntity = UserEntity()
userEntity.age = 17
userEntity.imgurl = "url"
userEntity.password = "123456"
userEntity.userName = "张珊"
userEntity.sex = "女"
userEntity.phone = "1560000xxxx"
userEntity.userId = "1"
getRepository().update(userEntity)
}
插入、修改、获取等全部代码
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 = "张珊"
userEntity.sex = "女"
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 = "张珊"
userEntity.sex = "女"
userEntity.phone = "1560000xxxx"
userEntity.userId = "1"
getRepository().update(userEntity)
}
private fun onObtain() {
getRepository().getUser().observe(this, Observer {
Log.d(TAG, it.password ?: "")
})
}
}