公司网站如何做的美丽,资讯网站排版,网站模板带有sql后台下载,所得税 网站建设费文章目录 一、Room简介二、用RoomViewModelLiveData增删改查数据三、下载源码 一、Room简介
Room是Google推出的数据库框架#xff0c;是一个 ORM (Object Relational Mapping)对象关系映射数据库、其底层还是对SQLite的封装。
Room包含三个主要组件#xff1a;
数据库类ViewModelLiveData增删改查数据三、下载源码 一、Room简介
Room是Google推出的数据库框架是一个 ORM (Object Relational Mapping)对象关系映射数据库、其底层还是对SQLite的封装。
Room包含三个主要组件
数据库类DataBase用于保存数据库并作为应用持久性数据底层连接的主要访问点。数据实体Entity用于表示应用的数据库中的表。数据访问对象 (DAO)提供您的应用可用于查询、更新、插入和删除数据库中的数据的方法。 Entity 表结构实体PrimaryKey 主键ColumnInfo 列/字段信息
二、用RoomViewModelLiveData增删改查数据
用 Entity、Dao、Database 操作数据库 数据库的每个表都对应一个Entity一个DaoDao负责增删改查操作
项目RoomDemo如下图 在build.gradle添加如下依赖
plugins {id com.android.applicationid kotlin-androidid kotlin-android-extensionsid kotlin-kapt
}dependencies {def room_version 2.3.0implementation androidx.room:room-runtime:$room_versionannotationProcessor androidx.room:room-compiler:$room_versionkapt androidx.room:room-compiler:$room_version
}首先创建一个数据表Student。先创建包名在com.bignerdranch.roomdemo下创建一个db包db下创建bean包bean包下创建Student类。
package com.bignerdranch.roomdemo.db.beanimport androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import org.jetbrains.annotations.NotNullEntity(tableName student)
class Student {NotNullPrimaryKey(autoGenerate true)ColumnInfo(name id, typeAffinity ColumnInfo.INTEGER)var id 0NotNullColumnInfo(name name, typeAffinity ColumnInfo.TEXT)var name: StringNotNullColumnInfo(name age, typeAffinity ColumnInfo.TEXT)var age: String/*** Room会使用这个构造器来存储数据也就是当你从表中得到Student对象时候Room会使用这个构造器*/constructor(id: Int, name: String, age: String) {this.id idthis.name namethis.age age}/*** 由于Room只能识别和使用一个构造器如果希望定义多个构造器你可以使用Ignore标签让Room忽略这个构造器* 同样Ignore标签还可用于字段使用Ignore标签标记过的字段Room不会持久化该字段的数据*/Ignoreconstructor(name: String, age: String) {this.name namethis.age age}
}这个Entity就是表示数据库中的表Student类对应就是Student表PrimaryKey表示主键这里是idautoGenerate true 是自增NonNull表示不为空。 ColumnInfo表示表中的列名name name表示列名的值。
下面在db包下新建一个dao包创建StudentDao里面的代码如下
package com.bignerdranch.roomdemo.db.daoimport androidx.lifecycle.LiveData
import androidx.room.*
import com.bignerdranch.roomdemo.db.bean.StudentDao
interface StudentDao {Insertfun insertStudent(student: Student?)Deletefun deleteStudent(student: Student?)Updatefun updateStudent(student: Student?)Query(SELECT * FROM student)fun getStudentList(): LiveDataListStudent??? //希望监听学生表的变化为其加上LiveDataQuery(SELECT * FROM student WHERE id :id)fun getStudentById(id: Int): Student?
}StudentDao是一个接口主要是定义了一些方法通过注解在编译的时候会生成实现类。 然后新建main/assets/databases并在其中放置student.db文件其位置如下 用SQLite软件导入students.db文件如下图 然后在MyDatabase.kt中用createFromAsset()方法从assets/database/students.db创建Room数据库下面是数据库的创建在db包下新建一个MyDatabase类继承RoomDatabase代码如下
package com.bignerdranch.roomdemo.dbimport android.content.Context
import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.bignerdranch.roomdemo.db.bean.Student
import com.bignerdranch.roomdemo.db.dao.StudentDaoDatabase(entities [Student::class], exportSchema false, version 1)
abstract class MyDatabase() : RoomDatabase() {abstract fun studentDao(): StudentDao?companion object {private val DATABASE_NAME my_dbprivate var databaseInstance: MyDatabase? nullSynchronized //已同步fun getInstance(context: Context): MyDatabase? {if (databaseInstance null) {databaseInstance Room.databaseBuilder(context.applicationContext,MyDatabase::class.java,DATABASE_NAME).createFromAsset(databases/student.db).fallbackToDestructiveMigration()
// .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_1_3, MIGRATION_3_4).build()}return databaseInstance}val MIGRATION_1_2: Migration object : Migration(1, 2) {override fun migrate(database: SupportSQLiteDatabase) {//do somethingLog.d(MyDatabase, MIGRATION_1_2)}}private val MIGRATION_2_3: Migration object : Migration(2, 3) {override fun migrate(database: SupportSQLiteDatabase) {//do somethingLog.d(MyDatabase, MIGRATION_2_3)}}private val MIGRATION_1_3: Migration object : Migration(1, 3) {override fun migrate(database: SupportSQLiteDatabase) {//do somethingLog.d(MyDatabase, MIGRATION_1_3)}}val MIGRATION_3_4: Migration object : Migration(3, 4) {override fun migrate(database: SupportSQLiteDatabase) {Log.d(MyDatabase, MIGRATION_3_4)database.execSQL(CREATE TABLE temp_Student ( id INTEGER PRIMARY KEY NOT NULL, name TEXT, age TEXT))database.execSQL(INSERT INTO temp_Student (id, name, age) SELECT id, name, age FROM Student)database.execSQL(DROP TABLE Student)database.execSQL(ALTER TABLE temp_Student RENAME TO Student)}}}
}这里的Database注解表示这个类是用来操作数据库的entities [Student::class]表示当前数据库中的表只有一个Student表多的表用应用逗号隔开。version 1表示数据库的版本可以做数据库的升级操作。createFromAsset()是Room库中提供的。
注意这是一个抽象类在编译时Room会帮助构建实现类。
现在运行一下手机或者模拟器都可以。然后什么都不用去做。 可以查看到MyDatabase和StudentDao的实现类都自动生成了。
ViewModel内通过 Room.Database查到LiveData数据在外部监听LiveData 当 Room变化时通过ViewModel内的LiveData通知页面数据的变化架构如下 新建StudentViewModel类该类继承自AndroidViewModel其中有Database和LiveData代码如下
package com.bignerdranch.roomdemo.jetpackroomwithlivedataandviewmodeltestimport android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import com.bignerdranch.roomdemo.db.MyDatabase
import com.bignerdranch.roomdemo.db.bean.Studentclass StudentViewModel(application: Application) : AndroidViewModel(application) {private val myDatabase: MyDatabase?val liveDataStudent: LiveDataListStudent???init {myDatabase MyDatabase.getInstance(application)liveDataStudent myDatabase!!.studentDao()!!.getStudentList()}}表操作无非就是那么几个增删改查但是为了更直观的显示结果需要对UI做一些改动。
在工程的build.gradle中增加repositories闭包中增加jitpack库。 然后在app的build.gradle中的dependencies{}比包中增加
implementation com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.61. 修改布局 Sync一下下面修改一下页面的布局文件activity_main.xml
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:orientationverticalButtonandroid:idid/btnInsertStudentandroid:layout_widthwrap_contentandroid:layout_heightwrap_contentandroid:layout_gravitycenter_horizontalandroid:layout_margin12dpandroid:textAdd a Studentandroid:textAllCapsfalse /androidx.recyclerview.widget.RecyclerViewandroid:idid/recyclerViewandroid:layout_widthmatch_parentandroid:layout_heightwrap_content /
/LinearLayout这里就是一个按钮和一个列表下面创建列表的item布局 在layout下新建一个list_item_student.xml布局代码如下
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:orientationhorizontalandroid:paddingTop12dpandroid:paddingBottom12dpTextViewandroid:idid/tvIdandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:layout_weight1android:gravitycenter /TextViewandroid:idid/tvNameandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:layout_weight1android:gravitycenter /TextViewandroid:idid/tvAgeandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:layout_weight1android:gravitycenter //LinearLayout新建dialog_layout_student.xml布局如下
?xml version1.0 encodingutf-8?
LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/androidandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:orientationhorizontalEditTextandroid:idid/etNameandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:layout_weight1android:autofillHintsandroid:hintName /EditTextandroid:idid/etAgeandroid:layout_widthmatch_parentandroid:layout_heightwrap_contentandroid:layout_weight1android:autofillHintsandroid:hintAge //LinearLayout在com.bignerdranch.roomdemo下新建一个adapter包包下新建StudentAdapter类作为列表数据的适配器。代码如下 2. 列表适配器
package com.bignerdranch.roomdemo.adapterimport com.bignerdranch.roomdemo.R
import com.bignerdranch.roomdemo.db.bean.Student
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import kotlinx.android.synthetic.main.list_item_student.view.*class StudentAdapter(layoutResId: Int R.layout.list_item_student) :BaseQuickAdapterStudent, BaseViewHolder(layoutResId) {override fun convert(holder: BaseViewHolder, item: Student) {holder.itemView.run {tvId.text item.id.toString()tvName.text item.nametvAge.text item.age}}
}然后在MainActivity中初始化List实例化StudentViewModel并监听其LiveData的变化代码如下
package com.bignerdranch.roomdemoimport android.content.DialogInterface
import android.os.AsyncTask
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.bignerdranch.roomdemo.adapter.StudentAdapter
import com.bignerdranch.roomdemo.db.MyDatabase
import com.bignerdranch.roomdemo.db.bean.Student
import com.bignerdranch.roomdemo.jetpackroomwithlivedataandviewmodeltest.StudentViewModel
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemLongClickListener
import kotlinx.android.synthetic.main.activity_main.recyclerView/**** date*/
class MainActivity : AppCompatActivity(), OnItemLongClickListener {private val mStudentAdapter by lazy {StudentAdapter().apply {setOnItemLongClickListener(thisMainActivity)}}private var myDatabase: MyDatabase? nullprivate var studentList: MutableListStudent? nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)findViewByIdView(R.id.btnInsertStudent).setOnClickListener {openAddStudentDialog()}studentList ArrayList()val layoutManager LinearLayoutManager(thisMainActivity)layoutManager.orientation LinearLayoutManager.VERTICALrecyclerView.layoutManager layoutManagerrecyclerView.adapter mStudentAdapter
// mStudentAdapter.setList(studentList)myDatabase MyDatabase.getInstance(this)val studentViewModel: StudentViewModel ViewModelProvider(this)[StudentViewModel::class.java]studentViewModel.liveDataStudent!!.observe(this) { students -(studentList as ArrayListStudent?).clear()(studentList as ArrayListStudent?).addAll(students!!)
// studentAdapter2!!.notifyDataSetChanged()mStudentAdapter.setList(studentList)mStudentAdapter.notifyDataSetChanged()}}private fun updateOrDeleteDialog(student: Student?) {val options arrayOf(更新, 删除)AlertDialog.Builder(thisMainActivity).setTitle().setItems(options) { _, which -if (which 0) {openUpdateStudentDialog(student)} else if (which 1) {if (student ! null) {DeleteStudentTask(student).execute()}}}.show()}private fun openAddStudentDialog() {val customView: View this.layoutInflater.inflate(R.layout.dialog_layout_student, null)val etName customView.findViewByIdEditText(R.id.etName)val etAge customView.findViewByIdEditText(R.id.etAge)val builder AlertDialog.Builder(thisMainActivity)val dialog builder.create()dialog.setTitle(Add Student)dialog.setButton(DialogInterface.BUTTON_POSITIVE, OK) { dialog, which -if (TextUtils.isEmpty(etName.text.toString()) || TextUtils.isEmpty(etAge.text.toString())) {Toast.makeText(thisMainActivity, 输入不能为空, Toast.LENGTH_SHORT).show()} else {InsertStudentTask(etName.text.toString(), etAge.text.toString()).execute()}}dialog.setButton(DialogInterface.BUTTON_NEGATIVE,CANCEL) { dialog, which - dialog.dismiss() }dialog.setView(customView)dialog.show()}private fun openUpdateStudentDialog(student: Student?) {if (student null) {return}val customView: View this.layoutInflater.inflate(R.layout.dialog_layout_student, null)val etName customView.findViewByIdEditText(R.id.etName)val etAge customView.findViewByIdEditText(R.id.etAge)etName.setText(student.name)etAge.setText(student.age)val builder AlertDialog.Builder(thisMainActivity)val dialog builder.create()dialog.setTitle(Update Student)dialog.setButton(DialogInterface.BUTTON_POSITIVE, OK) { dialog, which -if (TextUtils.isEmpty(etName.text.toString()) || TextUtils.isEmpty(etAge.text.toString())) {Toast.makeText(thisMainActivity, 输入不能为空, Toast.LENGTH_SHORT).show()} else {UpdateStudentTask(student.id,etName.text.toString(),etAge.text.toString()).execute()}}dialog.setButton(DialogInterface.BUTTON_NEGATIVE,CANCEL) { dialog, which - dialog.dismiss() }dialog.setView(customView)dialog.show()}private inner class InsertStudentTask(var name: String, var age: String) :AsyncTaskVoid?, Void?, Void?() {override fun doInBackground(vararg params: Void?): Void? {myDatabase!!.studentDao()!!.insertStudent(Student(name, age))return null}}private inner class UpdateStudentTask(var id: Int, var name: String, var age: String) :AsyncTaskVoid?, Void?, Void?() {override fun doInBackground(vararg params: Void?): Void? {myDatabase!!.studentDao()!!.updateStudent(Student(id, name, age))return null}}private inner class DeleteStudentTask(var student: Student) : AsyncTaskVoid?, Void?, Void?() {override fun doInBackground(vararg params: Void?): Void? {myDatabase!!.studentDao()!!.deleteStudent(student)return null}}override fun onItemLongClick(adapter: BaseQuickAdapter*, *,view: View,position: Int): Boolean {updateOrDeleteDialog((studentList as ArrayListStudent?)[position])return true}
}运行后当LiveData数据变化时更新UI即可而不需要每次增删改后都必须用QueryStudentTask() 来手动查询一次数据库简化了系统效果如下 三、下载源码
下载源码github地址https://github.com/caobin10/RoomDemo