I am new to using LiveData
and ViewModels
and I don't fully understand how the data is updated.
According to the Android Dev site:
Instead of updating the UI every time the app data changes, your observer can update the UI every time there's a change.
That sentence doesn't make sense to me. I'm using a Sqlite database (without Room) and I'm asynchronously getting the data in the getItems()
method of the ViewModel
. Does that mean when data is added or updated in the database, the LiveData
will automatically detect it and onChange
is called?
According to the Android dev site, it says to begin observing a LiveData
object in onCreate
. Before using LiveData
, I was refreshing the data in onResume
by querying the database then calling notifyDataSetChanged()
.
This code I have now displays the data when the Fragment
loads, but if I delete or add new data to the database, the UI does not reflect the change. I just think I don't have a basic understanding of how LiveData
works and I can't find a good explanation anywhere.
Help me StackOverflow, you're my only hope.
public class MyViewModel extends AndroidViewModel {
private MutableLiveData<List<String>> items;
private Application application;
public MyViewModel(@NonNull Application application) {
super(application);
this.application = application;
}
public MutableLiveData<List<String>> getItems() {
if (items == null) {
items = new MutableLiveData<>();
getItems();
}
return items;
}
private void getItems() {
List<String> items = GetItems(); //async process
this.items.setValue(items)
}
}
public class ListFragment extends Fragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyViewModel model = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
final Observer<List<String>> observer = new Observer<List<String>>() {
@Override
public void onChanged(List<String> items) {
//update UI
}
};
model.getItems().observe(this, observer);
}
}