ASTeam February 2016

Android addToBackStack(null) not working, closing the app

In my app I am using Fragments in one Activity, and I am trying to replace them. This works fine, but on back press I want to switch to previous fragment. I found addToBackStack() method but it is not working. Here is the code in MainActivity:

MainActivity.java:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fragment1 fragment1 = new Fragment1();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(android.R.id.content, fragment1);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

public void changeFragment(Fragment f)
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(android.R.id.content, f);
    fragmentTransaction.commit();
}

@Override
public void onBackPressed()
{
    if (getSupportFragmentManager().getBackStackEntryCount() > 0 )
    {
        getSupportFragmentManager().popBackStackImmediate();
    }
    else
    {
        super.onBackPressed();
    }
}
}

Fragment1.java:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Fragment1 extends Fragment
{
private Button buttonFragment1;

public Fragment1() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                       

Answers


Rohit5k2 February 2016

Change your method like this

public void changeFragment(Fragment f)
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(android.R.id.content, f);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

Then you should remove fragmentTransaction.addToBackStack(null); from onCreate of MainActivity.

Also, in Fragment1 code inside onActivityCreated should be moved to onCreateView.

Post Status

Asked in February 2016
Viewed 1,212 times
Voted 10
Answered 1 times

Search




Leave an answer