Guy Bridge Guy Bridge - 2 months ago 23
Android Question

Replace fragment in ViewPager - Getting NPE

I have searched the other answers regarding how to replace a fragment within a viewPager but to no avail.

The setup is the usual, I have 2 fragments.

[Fragment1][Fragment2]

From the action bar I have a search button which starts a new Intent in overlay mode (Google Search) then in onActivityResult I would like to replace the current fragment with the new fragment.

I have the SearchFragment complete and it works if I add it as a 3rd Fragment in the tabs. However I just want to replace Fragment2 with the new search fragment.

I have a sectionsPagerAdapter class it that helps.

So when I click the searchButton in the actionbar I have this code firing in onActivityResult()

SearchFragment searchFragment = new SearchFragment();
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.container, searchFragment)
.addToBackStack(null)
.commit();


However the app crashes with a error:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.app/com.example.MainActivityTabs}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

at com.example.MainActivityTabs.onActivityResult(MainActivityTabs.java:168)


168 is the .commit();

If I have the fragment transaction firing when the button is pressed it at least doesn't crash but it clears both fragments in the pager. So I think there is two issues in there.

Thanks

Answer

I came through same problem, It won't work if you a commit a fragment in onActivityResult()

But you can achieve this by

boolean replaceFragment=false;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
       replaceFragment = true;
}

@Override
public void onResume() {
    super.onResume();
    if (replaceFragment) {
        replaceFragment = false;
        //do your fragment transaction in handler with some time
        new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                   //Do your fragment transaction here
                }
        }, 500);
    }
}

For more about fragment transactions and the error see https://medium.com/@bherbst/the-many-flavors-of-commit-186608a015b1#.9gnzh4wqi

Comments