Livedata+viewmodel+Repository+Room

title:数据库读写:Room+LiveData+ViewModel+Repository

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中实例化数据库(另一种做法是在Repository),并对外暴露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();
    }
});
posted @ 2023-04-23 23:59  ZZX11  阅读(53)  评论(0编辑  收藏  举报