Reputation: 640
Here's what I am trying to do.
I have 2 fragments hosted in MainActivity.
Fragment 1 has just a couple of widgets to update. Fragment 2 has a recycler view to display the list of items.
I first get an instance of the data class and call its fetchData method.
The fetchData() method communicates with the local database to first see if my data is already stored in my local database.
If it is stored, then it simply returns that data and the recycler view in fragment 2 simply display that data.
But the problem arises when I have to fetch fresh data from the internet if data in my local database is not already present which is an asynchronous call. (The library I am using to call web API is Volly)
Now I am confused how to tell Fragment 1 and Fragment 2 to use the updated data once the database is updated?
Upvotes: 2
Views: 547
Reputation: 8585
A convenient way to connect activity and fragments inside it is provided by architecture components.
Create a ViewModel, that will host your data class instance. https://developer.android.com/topic/libraries/architecture/viewmodel.html#implement
Get view model reference in both your fragments.
final MyModel viewModel = ViewModelProviders.of(getActivity()).get(MyModel.class);
Make your ViewModel expose results of your data class as LiveData. https://developer.android.com/topic/libraries/architecture/livedata.html
private MutableLiveData<String> mCurrentData;
public MutableLiveData<String> getCurrentData() {
if (mCurrentName == null) {
mCurrentData = new MutableLiveData<String>();
}
return mCurrentData;
}
public void updateData() {
getCurrentData().setValue(myDataClass.getNewData());
}
Subscribe to the provided live data in both your fragment your.
// Get the ViewModel.
mModel = ViewModelProviders.of(getActivity()).get(MyModel.class);
// Create the observer which updates the UI.
final Observer<String> myObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newData) {
// do something with the new data
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentData().observe(this, myObserver);
Using this approach both your fragments will get the same updates in your myObserver
instances in both fragments from the ViewModel.
Here you can find a more detailed guide.
Upvotes: 2