How to remove previous fragment before call the activity I have GridView Which is showing in fragment, the GridView contain the number of items, the number of fragments will be open when i click on any item.
It's working fine, but after opened fragment when i click on back press the fragment is removed but the problem is when i opened activity after that fragment back press the previous fragment is still showing.
I have implemented code as below in backpress of MainActivity
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.activity_main_content_fragment);

if (currentFragment instanceof Home) {
removeFragmetns();
} else if (currentFragment instanceof RemarksFragment) {

} else {
getSupportFragmentManager().popBackStackImmediate();
}

and removefragments method is
public void removeFragmetns() {
FragmentManager fm = getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
    }

When i call the fragment and activity
In Swich Case OnClickListener
 fragmentClass = SyncFragment.class;
GlobalConstant.whichFragment = "data";
title = web[position];

after the switch case
fragmentManager.beginTransaction()
.addToBackStack(null)
.replace(R.id.activity_main_content_fragment, fragment).commit();

Calling the activity in switch case onclicklistener
fragmentManager.popBackStack();
Intent intentTasks = new Intent(getActivity(), TasksActivity.class);
startActivity(intentTasks);