0

I need to count my fragment, I used getbackstackentrycount, but it always return 0. Can someone tell me whats wrong with my code?

here my code MainActivity.java

package com.example.bams.taskagain;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.bams.taskagain.Fragment.FragmentOne;

public class MainActivity extends AppCompatActivity {
Button btn;
FragmentManager fm = getFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.fragOne);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fm.beginTransaction().add(R.id.content, new FragmentOne()).addToBackStack("aa").commit();
            //Toast.makeText(getBaseContext(), "text", Toast.LENGTH_LONG).show();
        }
    });

}

}

and here is my fragment class

package com.example.bams.taskagain.Fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.bams.taskagain.R;

/**
 * Created by jack on 25/02/2017.
 */

public class FragmentOne extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("Total back stack "+ ((AppCompatActivity)getActivity()).getSupportFragmentManager().getBackStackEntryCount());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_one,container,false);

        return rootView;
       }
    }

can someone help me with my code? I just want to get the BackStack count that my fragement has.

jack
  • 11
  • 4

1 Answers1

0

You're using android.app.Fragment and android.app.FragmentManager but using getSupportFragmentManager() to get back stack entry count.

Use

getFragmentManager().getBackStackEntryCount()

getFragmentManager() is used if your fragment is android.app.Fragment and getSupportFragmentManager() if your fragment is android.support.v4.fragment.

For more info on these fragments, take a look at Difference between android.app.Fragment and android.support.v4.app.Fragment

Community
  • 1
  • 1
Srikar Reddy
  • 3,650
  • 4
  • 36
  • 58