此次文章来自知乎,总结了前辈的见解!!!
上一篇文章中,我们介绍了《Room的基本使用》。每次数据库中的数据发生变化后,我们都需要开启一个工作线程去获取数据库中的内容。这让我们觉得不方便,我们希望数据在发生变化时,我们能自动收到通知,这就是LiveData。
LiveData通常结合ViewModel一起使用。我们知道ViewModel是用来存放数据的,因此我们可以将数据库放在ViewModel中进行实例化。但数据库在实例化的时候需要Context,而ViewModel不能传入任何带有Context引用的对象,所以,我们不能直接使用ViewModel,而应该用它的子类AndroidViewModel,它可以接受Application作为参数,而这个Application刚好可以被我们用于数据库的实例化。
通常我们的应用程序只会实例化一个数据库对象,并在应用程序的整个生命周期中使用这一个对象,恰好AndroidViewModel引入Application作为Context,AndroidViewModel的生命周期也伴随着整个应用程序的生命周期。
1.修改学生表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);
}
2.创建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;
}
}
3.在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();
}
});