Guy Bridge Guy Bridge - 1 month ago 11
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.


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(, searchFragment)

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 {}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

at com.example.MainActivityTabs.onActivityResult(

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.



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;

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

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

For more about fragment transactions and the error see