Room框架支持的LiveData会自动监听数据库的变化,当数据库发生变化的时候,会调用onChanged函数更新UI
1.MainActivity
package com.tiger.room2;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private StudentRecyclerViewAdapter adapter;
private StudentViewModel studentViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recycleView = findViewById(R.id.recycleView);
recycleView.setLayoutManager(new LinearLayoutManager(this));
List<Student> students = new ArrayList<>();
adapter = new StudentRecyclerViewAdapter(students);
recycleView.setAdapter(adapter);
studentViewModel = new ViewModelProvider(this).get(StudentViewModel.class);
//自动更新,给LiveData 添加监听
LiveData<List<Student>> listLiveData = studentViewModel.queryAllStudentsLive();
List<Student> value = listLiveData.getValue();
if (value==null) {
Log.d("ning","value is null");
}else {
Log.d("ning",value.toString());
}
listLiveData.observe(this, new Observer<List<Student>>() {
@Override
public void onChanged(List<Student> students) {
Log.d("ning",listLiveData.getValue().toString());
adapter.setStudents(students);
adapter.notifyDataSetChanged();
}
});
}
public void mInsert(View view) {
Student jack = new Student("Jack", 20);
Student rose = new Student("rose", 23);
studentViewModel.insertStudent(jack, rose);
}
public void mDelete(View view) {
Student student = new Student(1);
studentViewModel.deleteStudent(student);
}
public void mUpdate(View view) {
Student rose = new Student(3, "wqeqasdaddqweqwe", 212313);
studentViewModel.updateStudent(rose);
}
public void mClear(View view) {
studentViewModel.deleteAllStudent();
}
}
2.MyDataBase
package com.tiger.room2;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
//一定要写成抽象类
@Database(entities = {Student.class}, version = 1, exportSchema = false)
public abstract class MyDataBase extends RoomDatabase {
private static final String DATABASE_NAME = "my_db.db";
private static MyDataBase mInstance;
public static MyDataBase getInstance(Context context){
if (mInstance == null){
synchronized(MyDataBase.class){
if (mInstance == null){
mInstance = Room.databaseBuilder(context.getApplicationContext(), MyDataBase.class,DATABASE_NAME)
// .allowMainThreadQueries() 允许主线程操作数据库
.build();
}
}
}
return mInstance;
}
public abstract StudentDao getStudentDao();//room自动实现
}
3.Student
package com.tiger.room2;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
@Entity(tableName = "student")
public class Student {
@PrimaryKey(autoGenerate = true)//主键 自增
@ColumnInfo(name = "id",typeAffinity = ColumnInfo.INTEGER)//指定列名 类型
public int id;
@ColumnInfo(name = "name",typeAffinity = ColumnInfo.TEXT)//指定列名 类型
public String name;
@ColumnInfo(name = "age",typeAffinity = ColumnInfo.INTEGER)//指定列名 类型
public int age;
// @Ignore
// public boolean flag; 属性也可以忽略 ,代表它不是数据库的一列
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Ignore //room忽略此构造方法 构造对象
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Ignore
public Student(int id) {
this.id = id;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
4.StudentDao
package com.tiger.room2;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
@Dao
public interface StudentDao {
@Insert
void insert(Student... students);
@Delete
void deleteStudent(Student... students);
@Query("delete from student")
void deleteAll();
@Update
void updateStudent(Student... students);
@Query("select * from student")
LiveData<List<Student>> getAllStudentsLive();
@Query("select * from student where id = :id")
Student getStudentById(int id);
}
5.StudentRecyclerViewAdapter
package com.tiger.room2;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
/**
* @author ningchuanqi
* @version V1.0
*/
public class StudentRecyclerViewAdapter extends RecyclerView.Adapter {
List<Student> students;
public StudentRecyclerViewAdapter(List<Student> students) {
this.students = students;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
return new MyViewHoder(root);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Student student = students.get(position);
TextView tvId = holder.itemView.findViewById(R.id.tvId);
tvId.setText(String.valueOf(student.id));
TextView tvName = holder.itemView.findViewById(R.id.tvName);
tvName.setText(student.name);
TextView tvAge = holder.itemView.findViewById(R.id.tvAge);
tvAge.setText(String.valueOf(student.age));
}
@Override
public int getItemCount() {
return students.size();
}
static class MyViewHoder extends RecyclerView.ViewHolder {
public MyViewHoder(@NonNull View itemView) {
super(itemView);
}
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
6.StudentReposity
package com.tiger.room2;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import androidx.lifecycle.LiveData;
import java.util.List;
public class StudentRepository {
private StudentDao studentDao;
public StudentRepository(Context context) {
MyDataBase dataBase = MyDataBase.getInstance(context);
this.studentDao = dataBase.getStudentDao();
}
public void insertStudent(Student ... students) {
new InsertStudentTask(studentDao).execute(students);
}
class InsertStudentTask extends AsyncTask<Student, Void, Void> {
private StudentDao studentDao;
public InsertStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Student ... students) {
studentDao.insert(students);
return null;
}
}
public void updateStudent(Student... students) {
new UpdateStudentTask(studentDao).execute(students);
}
class UpdateStudentTask extends AsyncTask<Student, Void, Void> {
private StudentDao studentDao;
public UpdateStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Student... students) {
studentDao.updateStudent(students);
return null;
}
}
//除非服务器崩了,要不然代码不可能错
public void deleteStudent(Student ... student) {
new DeleteStudentTask(studentDao).execute(student);
}
class DeleteStudentTask extends AsyncTask<Student, Void, Void> {
private StudentDao studentDao;
public DeleteStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Student... students) {
studentDao.deleteStudent(students);
return null;
}
}
public void deleteAllStudent() {
new DeleteAllStudentTask(studentDao).execute();
}
class DeleteAllStudentTask extends AsyncTask<Void, Void, Void> {
private StudentDao studentDao;
public DeleteAllStudentTask(StudentDao studentDao) {
this.studentDao = studentDao;
}
@Override
protected Void doInBackground(Void... voids) {
studentDao.deleteAll();
return null;
}
}
public LiveData<List<Student>> queryAllStudentsLive() {
return studentDao.getAllStudentsLive();
}
// class GetAllStudentTask extends AsyncTask<Void,Void,Void>{
//
// private StudentDao studentDao;
//
// public GetAllStudentTask(StudentDao studentDao) {
// this.studentDao = studentDao;
// }
//
// @Override
// protected Void doInBackground(Void... voids) {
// List<Student> students = studentDao.getAllStudent();
// adapter.setStudents(students);
// return null;
// }
//
// @Override
// protected void onPostExecute(Void aVoid) {
// super.onPostExecute(aVoid);
// adapter.notifyDataSetChanged();
// }
// }
}
7.StudentViewModel
package com.tiger.room2;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class StudentViewModel extends AndroidViewModel {
private StudentRepository studentRepository;
public StudentViewModel(@NonNull Application application) {
super(application);
this.studentRepository = new StudentRepository(application);
}
public void insertStudent(Student ... students){
studentRepository.insertStudent(students);
}
public void deleteStudent(Student ... students){
studentRepository.deleteStudent(students);
}
public void updateStudent(Student ... students){
studentRepository.updateStudent(students);
}
public void deleteAllStudent(){
studentRepository.deleteAllStudent();
}
public LiveData<List<Student>> queryAllStudentsLive(){
return studentRepository.queryAllStudentsLive();
}
}
8.xml
<?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=".MainActivity">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.2" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<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.1" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycleView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.709"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline3" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="增加"
android:onClick="mInsert"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintEnd_toStartOf="@+id/guideline4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除"
android:onClick="mDelete"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline4"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改"
android:onClick="mUpdate"
app:layout_constraintBottom_toTopOf="@+id/guideline3"
app:layout_constraintEnd_toStartOf="@+id/guideline4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline5" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="清空"
android:onClick="mClear"
app:layout_constraintBottom_toTopOf="@+id/guideline3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline4"
app:layout_constraintTop_toTopOf="@+id/guideline5" />
</androidx.constraintlayout.widget.ConstraintLayout>
9.item.xml
<?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="wrap_content"
android:paddingVertical="10dip">
<TextView
android:id="@+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
tools:text="1"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
tools:text="Jack"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintStart_toStartOf="@+id/guideline"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
tools:text="18"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.8" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.2" />
</androidx.constraintlayout.widget.ConstraintLayout>