1. Android Jetpack学习笔记4中介绍了《Room的基本使用》。每次数据库中的数据发生变化后,我们都需要开启一个工作线程去获取数据库中的内容。这让我们觉得不方便,我们希望数据在发生变化时,我们能自动收到通知,这就是LiveData。
2. LiveData通常结合ViewModel一起使用。我们知道ViewModel是用来存放数据的,因此我们可以将数据库放在ViewModel中进行实例化。但数据库在实例化的时候需要Context,而ViewModel不能传入任何带有Context引用的对象,所以,我们不能直接使用ViewModel,而应该用它的子类AndroidViewModel,它可以接受Application作为参数,而这个Application刚好可以被我们用于数据库的实例化。
3.修改学生表Dao文件。我们希望数据库中学生表发生变化的时候能够收到实时通知,因此需要修改学生表Dao文件。
@Dao
public interface StudentDao
{
@Insert
void insertStudent(Student student);
@Delete
void deleteStudent(Student student);
@Update
void updateStudent(Student student);
@Query("SELECT * FROM student")
LiveData<List<Student>> getStudentList();//希望监听学生表的变化,为其加上LiveData
@Query("SELECT * FROM student WHERE id = :id")
Student getStudentById(int id);
}
4.创建StudentViewModel,继承自AndroidViewModel。在StudentViewModel中实例化数据库,并对外暴露LiveData<List<Student>>。
public class StudentViewModel extends AndroidViewModel
{
private MyDatabase myDatabase;
private LiveData<List<Student>> liveDataStudent;
public StudentViewModel(@NonNull Application application)
{
super(application);
myDatabase = MyDatabase.getInstance(application);
liveDataStudent = myDatabase.studentDao().getStudentList();
}
public LiveData<List<Student>> getLiveDataStudent()
{
return liveDataStudent;
}
}
5.在Activity中实例化StudentViewModel,并监听LiveData的变化。
StudentViewModel studentViewModel = ViewModelProviders.of(this).get(StudentViewModel.class);
studentViewModel.getLiveDataStudent().observe(this, new Observer<List<Student>>()
{
@Override
public void onChanged(List<Student> students)
{
studentList.clear();
studentList.addAll(students);
studentAdapter.notifyDataSetChanged();
}
});
6.这样,当你对数据库进行增加,删除和修改操作的时候,onChange(List<Student> students)方法会被自动调用。你只需要在该方法内,通知Adapter刷新一下数据即可,其它什么都不用管。对比以前,我们在修改数据库后,还需要开启一个线程手动查询一次数据库,再更新Adapter,无疑LiveData可以大大减轻我们的工作量。
最后放一张效果图:
7.项目的源码地址如下: