I would like to notify ViewPagerAdapter that dataset changed in Loader.onLoadFinish callback function.
It is prevented because state of fragments might be saved.
From LoaderManager.LoaderCallbacks.onLoadFinished(Loader loader, D data) method documentation:
Note that normally an application is not allowed to commit fragment transactions while in this call, since it can happen after an activity's state is saved.`
How can I overcome this problem? How can I check in which state Activity is and commit Fragment transaction?
Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
At runtime, a FragmentManager can add, remove, replace, and perform other actions with fragments in response to user interaction. Each set of fragment changes that you commit is called a transaction, and you can specify what to do inside the transaction using the APIs provided by the FragmentTransaction class.
FragmentStateAdapter instead. Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.
setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Fragment fragment = new tasks(); FragmentManager fragmentManager = getActivity(). getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction(); fragmentTransaction. replace(R.
I've come with following solution:
Method changeCursorInOtherThread is used in onLoadFinished and onLoaderReset.
Handler is created in Activity:
private Handler mHandler = new Handler();
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mSaved = true;
}
private void changeCursorInOtherThread(final Cursor data) {
if(!mSaved){
mHandler.post(new Runnable() {
@Override
public void run() {
mViewPagerAdapter.changeCursor(data);
}
});
}
}
I had a similar problem. Wanted to show a DialogFragment after onLoadFinished(). As you said it's not possible to commit fragment transaction inside onLoadFinished(). But then I realized, that I could just implement LoaderCallbacks in the DialogFragment. And it works like a charm. Instead of listening for the Loader to finish its job within an Activity, I do it inside the Fragment.
You could do the same. Instead of implementing onLoadFinished() inside your activity you could just implement it inside Fragments which are placed in your ViewPager. Of course in some cases it doesn't make sense in a ViewPager, it depends on your data structure.
There's more discussion on this issue here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With