我决定优化代码,因此切换到liveData。我遵循了youtube(youtube link)上的教程,但由于用户未在适配器中存储任何列表,因此我不太了解当用户输入单词时如何过滤recyclerView。我在MainActivity上使用了一个简单的searchview过滤器系统。
此外,由于以下原因,我使用DiffUtil更新了recyclerView并更新了我的适配器:
noteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, adapter::submitList);
我的代码与视频几乎相同,但这是其中的一部分:
ViewModel:
public class NoteViewModel extends AndroidViewModel {
private NoteRepository repository;
private LiveData<List<Note>> allNotes;
public NoteViewModel(@NonNull Application application) {
super(application);
repository = new NoteRepository(application);
allNotes = repository.getAllNotes();
}
public void insert(Note note) {
repository.insert(note);
}
public void update(Note note) {
repository.update(note);
}
public void delete(List<Note> notes) {
repository.delete(notes);
}
public LiveData<List<Note>> getAllNotes() {
return allNotes;
}
}
我的存储库:
public class NoteRepository {
private NotesDAO notesDAO;
private LiveData<List<Note>> allNotes;
public NoteRepository(Application application) {
NotesDB database = NotesDB.getInstance(application);
notesDAO = database.notesDAO();
allNotes = notesDAO.getAllNotes();
}
public void insert(Note note) {
new InsertNoteAsyncTask(notesDAO).execute(note);
}
public void update(Note note) {
new UpdateNoteAsyncTask(notesDAO).execute(note);
}
public void delete(List<Note> note) {
new DeleteNoteAsyncTask(notesDAO).execute(note);
}
public LiveData<List<Note>> getAllNotes() {
return allNotes;
}
private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> { // SOME STUFF }
private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> { // SOME STUFF }
private static class DeleteNoteAsyncTask extends AsyncTask<List<Note>, Void, Void> { // SOME STUFF }
}