问题
I am using Android LiveData and Room Database to update a list.
I have a list of notes which have a tick to mark them as "DONE".
If they are marked done, I remove them from current list (not from database) so that they can be shown on another page.
But marking them done does not update my list.
DAO:
@Dao
public interface NoteDao {
@Query("SELECT * FROM notes WHERE isDone=0")
LiveData<List<Note>> getAll();
@Insert
void insert(Note note);
@Delete
void delete(Note note);
@Update
void update(Note note);
}
I have a onchecked listener in my adapter which handles the list clicks.
Note note = allNotes.get(position);
holder.mCheckBox.setListener(isChecked -> {
note.setIsDone(1);
mNoteDao.update(note);
notifyDataSetChanged();
});
I have put an observe function in activity.
mNoteDao.getAll().observe(this, notes -> {
if (notes != null && notes.size() > 0) {
img_no_notes.setVisibility(View.GONE);
txt_no_notes.setVisibility(View.GONE);
Collections.reverse(notes);
mAdapter.setItems(notes);
} else {
img_no_notes.setVisibility(View.VISIBLE);
txt_no_notes.setVisibility(View.VISIBLE);
}
});
The list is updated on relaunch. Thanks for your help.
回答1:
Your LiveData is responsible for reacting to Room database change only. If you want to change the list you need to create separate list or live data copy. Overall it is bad practice and LiveData+Room is used only for database change not memory instance. Imagine your LiveData object like a wrap over Room database.
回答2:
Your notes probably don't update themselves because your activity didn't change state. In that case you should update UI of changed note in your checkbox listener
From documentation:
LiveData takes in an observer and notifies it about data changes only when it is in STARTED or RESUMED state.
来源:https://stackoverflow.com/questions/48616419/android-livedata-list-not-updating