1

I have 2 fragments. In the first fragment there is a listview of items that I fetch from a server. and when I click a list item it will navigate to the second fragment with the details of the item I clicked. but when I press back and navigate to the previous fragment I have to go through the same process of fetching data from the server. Is there a way to avoid this ? can I navigate back to the previous fragment without making that network request again ?

slenderm4n
  • 292
  • 7
  • 15
  • Yes there are many ways to avoid. – Piyush Jan 16 '17 at 07:50
  • 1
    May be you are using replace for fragment transaction? Using add could help (so that the fragment is not removed). It would be helpful if you can add some code.You may refer this https://developer.android.com/guide/components/fragments.html#Transactions – Anindita Pani Jan 16 '17 at 07:50
  • Yes I'm using the replace method. is that the reason for that problem ? because of replacing the previous fragment has to go through on create state again when coming back ? – slenderm4n Jan 16 '17 at 07:52
  • @Piyush can you tell how ? – slenderm4n Jan 16 '17 at 07:56

1 Answers1

0

I'm not sure what method you used to go backwards. I think this is because you have override the onBackPress method and load the fragment through fragment transition. When back press it will initiate the fragment and create a new copy fragment object. If you can avoid that the network call won't call again.

You can try this. Override the onbackpress method.

@Override
public void onBackPressed() {
    int count = getSupportFragmentManager().getBackStackEntryCount();
    if (count == 0) {
        navigateActivity(HomeActivity.class);
    } else {
        getSupportFragmentManager().popBackStackImmediate();
    }
}

And start new fragment as follows,

public void switchFragment(Fragment frag) {
    String backStateName = fragment.getClass().getName();

    FragmentManager manager = getSupportFragmentManager();
    boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

    if (!fragmentPopped){
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.report_fragment, frag);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        fragmentTransaction.addToBackStack(backStateName);
        fragmentTransaction.commit();
   }

}

Hope this will help.

KZoNE
  • 1,249
  • 1
  • 16
  • 27