android – Navigating between two fragments on backpress-ThrowExceptions

Exception or error:

I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..

Fragment1 calling second fragment

    UserFragment frag = new UserFragment()
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        frag.setArguments(bundle);
        transaction.addToBackStack("UserActivity");
             transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();

In second Fragment i have implemented an interface OnBackpress and over riding the below method

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() != 0) {
        if(getFragmentManager().findFragmentByTag("UserActivity") != null){
            Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
            getFragmentManager().popBackStack();
        };
    }

}

But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks

How to solve:

You need to add you first fragment to back stack properly, you are doing it wrong in your first part of the code.
Use the following code instead.

    UserFragment frag = new UserFragment()
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    frag.setArguments(bundle);
    transaction.addToBackStack("UserActivity");
    transaction.replace(android.R.id.content, frag, "UserActivity");
    transaction.commit();

Also there is no need to add any code in your onBackPressed after above change.

###

First, you need to add your fragments to the backstack:

public static void addFragment(FragmentManager fragmentManager, Fragment fragment, int id){
    fragmentManager.beginTransaction().add(id, fragment).addToBackStack(null).commit();
}

Then you need to override the onBackPressed, which is a method gets called whenever a user clicks the back button:

@Override  
public void onBackPressed() { 
    super.onBackPressed();
    if(getSupportFragmentManager().getBackStackEntryCount() == 0){
        button.setVisibility(View.VISIBLE);
    }
}

###

please change to add() instead of replace() in your code..

    UserFragment frag = new UserFragment()
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    frag.setArguments(bundle);
    transaction.addToBackStack("UserActivity");
    transaction.add(android.R.id.content, frag, "UserActivity").addToBackStack(null);
    transaction.commit();

This will solve your problem.

Leave a Reply

Your email address will not be published. Required fields are marked *