Maybe I'm misunderstanding this all, but how do you edit data using Live Data/View Model/Repository? I see how query all the data, delete an entry, but I want to edit a particular field.
For example, I have 3 things I'm tracking. Date, Time, and Category.I need to be able to change what the category is.
I tried doing something like this in one of my activities:
budgetViewModel.getAllEntries().observe(this, new Observer<List<BudgetEntry>>() {
@Override
public void onChanged(List<BudgetEntry> budgetEntries) {
Log.i(TAG, "2nd Observer is going off");
if (manualUpdate == 1) {
Log.i(TAG, "MANUAL UPDATE");
budgetEntries.get(0).setCategory(updatedCategory);
manualUpdate = 0;
Log.i(TAG, "Budget Entries: " + budgetEntries.get(0).getCategory());
}
else {
Log.i(TAG, "No change");
}
}
});
}
}
But it doesn't change it permanently. Only for this instance I guess because the Log shows I changed the category, but when I reload the app or check another activity, it still shows the prior data.
I can't find any tutorials on this so any guidance would be most appreciated!
New View Model Changes. I get error cannot create instance of class:
public class BudgetViewModel extends AndroidViewModel {
private BudgetRepository budgetRepository;
//private LiveData<List<BudgetEntry>> allEntries;
LiveData<List<BudgetEntry>> _allEntries = budgetRepository.getAllEntries();
LiveData<List<BudgetEntry>> allEntries = Transformations.map(_allEntries, new Function<List<BudgetEntry>, List<BudgetEntry>>() {
@Override
public List<BudgetEntry> apply(List<BudgetEntry> input) {
return input;
}
});
public BudgetViewModel(@NonNull Application application) {
super(application);
budgetRepository = new BudgetRepository(application);
//allEntries = budgetRepository.getAllEntries();
}
public void insert (BudgetEntry budgetEntry) {
budgetRepository.insert(budgetEntry);
}
public void delete (BudgetEntry budgetEntry) {
budgetRepository.delete(budgetEntry);
}
public void deleteAllEntries () {
budgetRepository.deleteAllEntries();
}
public LiveData<List<BudgetEntry>> getAllEntries() {
return _allEntries;
}
public LiveData<Integer> getCount() {
return budgetRepository.getCount();
}
}
Thanks!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…