I have an Activity where users can see all notes in a RecyclerView. I load these notes as
LiveData<List<Note>>
using a ViewModel with Android Room database, so if the user edits a note, changes get reflected immediately.
Entity - Note.class
@Entity(tableName = "note_table")
public class Note {
@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private ArrayList<String> labels;
public Note(String title, ArrayList<String> labels) {
this.title = title;
this.labels = labels;
}
public ArrayList<String> getLabels() { return labels; }
public void setLabels(ArrayList<String> labels) { this.labels = labels; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
}
MainActivity.class
noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
@Override
public void onChanged(List<Note> notes) {
adapter.submitList(notes);
}
});
I also have a navigation drawer. There is a list of labels the user creates and can click on. For example, a note can have either one label: "to-do", or more: "shopping list" and "work". The user can then set those labels to the note. If they click the label, then the RecyclerView should be filtered for notes with that label.
For example the user clicks "work"
noteViewModel.setFilterAllData("work");
In NoteViewModel:
public class NoteViewModel extends AndroidViewModel {
private NoteRepository repository;
private LiveData<List<Note>> allNotes;
private MutableLiveData<Property> filterAllData = new MutableLiveData<>();
public NoteViewModel(@NonNull Application application) {
super(application);
repository = new NoteRepository(application);
allNotes = Transformations.switchMap(filterAllData, new Function<Property, LiveData<List<Note>>>() {
@Override
public LiveData<List<Note>> apply(Property input) {
return repository.filterAll(input);
}
});
}
void setFilterAllData(String labelName) {filterAllData.setValue(labelName);}
public long insert(Note note) { return repository.insert(note); }
public void update(Note note) { repository.update(note); }
public void delete(Note note) { repository.delete(note); }
LiveData<Note> getNote(int id) { return repository.getNote(id); }
In NoteRepository.class
LiveData<List<Note>> filterAll(String label) {
return noteDao.getNotesWLabel(label);
}
Dao - NoteDao.class
@Dao
public interface NoteDao {
@Insert
long insert(Note note);
@Update
void update(Note note);
@Delete
void delete(Note note);
@Query("SELECT * FROM note_table")
LiveData<List<Note>> getAllNotes();
@Query("SELECT * FROM note_table WHERE :label IN (labels)")
LiveData<List<Note>> getNotesWLabel(String label);
I've tried adding TypeConverters as suggested here: https://stackoverflow.com/a/45071364/4673960 but when I filter for a label, the recyclerview is empty.