做一个对学生表增删改查的小demo 来了解 一下room
第一步 添加依赖
implementation 'androidx.room:room-runtime:2.4.2'
kapt 'androidx.room:room-compiler:2.4.2'
记得勾选kapt
第二步 创建javaBean
package com.anguomob.jecpack.bean
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
@Entity(tableName = "student")
data class Student(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id", typeAffinity = ColumnInfo.INTEGER)
var id: Int,
@ColumnInfo(name = "name", typeAffinity = ColumnInfo.TEXT)
var name: String,
@ColumnInfo(name = "age", typeAffinity = ColumnInfo.INTEGER)
var age: Int
) {
@Ignore
constructor(name: String, age: Int) : this(0, name, age)
@Ignore
constructor(id: Int) : this(id, "",0)
}
这里呢。设置了自增id 又对每个属性针对数据库的字段做了标志
如果不需要某字段
可以使用@Ignore通配符
编写Dao类操作数据库
package com.anguomob.jecpack.dao
import androidx.room.*
import com.anguomob.jecpack.bean.Student
@Dao
interface StudentDao {
@Insert
fun insertStudent(vararg student: Student)
@Delete
fun deleteStudent(vararg student: Student)
@Update
fun updateStudent(vararg student: Student)
@Query("SELECT * from student")
fun queryAllStudent(): List<Student>
@Query("SELECT * from student where id = :id")
fun getStudentById(id: Int): List<Student>
}
编写
RoomDatabase 数据库类 来操作数据库对象
package com.anguomob.jecpack.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.anguomob.jecpack.bean.Student
import com.anguomob.jecpack.dao.StudentDao
import okhttp3.internal.Internal.instance
@Database(entities = [Student::class], version = 1, exportSchema = false)
abstract class MyDataBase : RoomDatabase() {
companion object {
var DATABASE_NAME = "my_db.db"
private lateinit var instance: MyDataBase
fun getSingle(context: Context): MyDataBase {
if (::instance.isInitialized.not()) {
instance = Room.databaseBuilder(
context.applicationContext,
MyDataBase::class.java,
DATABASE_NAME
)
.allowMainThreadQueries()//允许主线程操作数据库
.build();
}
return instance;
}
}
abstract fun getStudentDao(): StudentDao
}
编写页面布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.RoomActivity">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.09165527" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.19015048" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="insert"
android:text="增加"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintEnd_toStartOf="@+id/guideline8"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="change"
android:text="修改"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline8"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="delete"
android:text="删除"
app:layout_constraintBottom_toTopOf="@+id/guideline7"
app:layout_constraintEnd_toStartOf="@+id/guideline8"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline5" />
<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="query"
android:text="查询"
app:layout_constraintBottom_toTopOf="@+id/guideline7"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline8"
app:layout_constraintTop_toTopOf="@+id/guideline5" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline7" />
</androidx.constraintlayout.widget.ConstraintLayout>
main页面代码
package com.anguomob.jecpack.activity
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.anguomob.jecpack.R
import com.anguomob.jecpack.adapter.RoomAdapter
import com.anguomob.jecpack.bean.Student
import com.anguomob.jecpack.dao.StudentDao
import com.anguomob.jecpack.database.MyDataBase
import com.anguomob.jecpack.databinding.ActivityRoomBinding
class RoomActivity : AppCompatActivity() {
private lateinit var binding: ActivityRoomBinding
private lateinit var adapter: RoomAdapter
private lateinit var dataBase: MyDataBase
private lateinit var studentDao: StudentDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRoomBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.rv.layoutManager = LinearLayoutManager(this)
adapter = RoomAdapter()
binding.rv.adapter = adapter;
dataBase = MyDataBase.getSingle(this)
studentDao = dataBase.getStudentDao()
}
fun insert(view: View) {
val s1 = Student("Jack", 20)
val s2 = Student("Jack2", 21)
//主线程直接插入
// studentDao.insertStudent(s1)
//切换到子线程插入
InsertStudentTask(studentDao).execute(s1, s2)
}
fun change(view: View) {
val s1 = Student(1, "LiuAn", 27)
val s2 = Student(2, "LiuAN2", 27)
//主线程直接插入
// studentDao.insertStudent(s1)
//切换到子线程插入
UpDateStudentTask(studentDao).execute(s1, s2)
}
fun delete(view: View) {
DeleteStudentTask(studentDao).execute(Student(1))
}
fun query(view: View) {
GetAllStudentTask(studentDao).execute()
}
inner class InsertStudentTask(var studentDao: StudentDao) : AsyncTask<Student, Any, Any>() {
override fun doInBackground(vararg p0: Student) {
studentDao.insertStudent(*p0)
}
}
inner class GetAllStudentTask(var studentDao: StudentDao) : AsyncTask<Any, Any, Any>() {
override fun doInBackground(vararg p0: Any?) {
val queryAllStudent = studentDao.queryAllStudent()
adapter.setData(queryAllStudent);
}
override fun onPostExecute(result: Any?) {
super.onPostExecute(result)
adapter.notifyDataSetChanged()
}
}
inner class UpDateStudentTask(var studentDao: StudentDao) : AsyncTask<Student, Any, Any>() {
override fun doInBackground(vararg p0: Student) {
studentDao.updateStudent(*p0)
}
}
inner class DeleteStudentTask(var studentDao: StudentDao) : AsyncTask<Student, Any, Any>() {
override fun doInBackground(vararg p0: Student) {
studentDao.deleteStudent(*p0)
}
}
}
这里用到了Adapter
package com.anguomob.jecpack.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.anguomob.jecpack.R
import com.anguomob.jecpack.bean.Idol2
import com.anguomob.jecpack.bean.Student
import com.anguomob.jecpack.databinding.ItemBinding
import com.anguomob.jecpack.databinding.ItemRoomBinding
class RoomAdapter : RecyclerView.Adapter<RoomAdapter.RoomViewHolder>() {
var mData: MutableList<Student> = mutableListOf();
lateinit var itemRoomBinding: ItemRoomBinding
fun setData(data: List<Student>) {
this.mData.clear()
this.mData.addAll(data)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RoomViewHolder {
itemRoomBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.item_room,
parent,
false
)
return RoomViewHolder(itemRoomBinding);
}
override fun onBindViewHolder(holder: RoomViewHolder, position: Int) {
val data = mData.get(position);
holder.itemBinding.student = data;
}
override fun getItemCount(): Int {
return mData.size
}
class RoomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
lateinit var itemBinding: ItemRoomBinding
constructor(itemBinding: ItemRoomBinding) : this(itemBinding.root) {
this.itemBinding = itemBinding;
}
}
}
adapter布局代码
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="student"
type="com.anguomob.jecpack.bean.Student" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="40dp">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.7" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.3" />
<TextView
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(student.id)}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline9"
app:layout_constraintHorizontal_bias="0.46"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{student.name}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline3"
app:layout_constraintStart_toStartOf="@+id/guideline9"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(student.age)}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline3"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
我们虽然开启了主线程可以操作数据库 但是为了高效还是用内部类+
AsyncTask的方式抽取到了外面