I need to know, In which fragment callback method, we should call a web service by which after come back to fragment web service should not call again.
For example.
Put everything that you want to call just once in onCreate() method. For example your API call, list, adapter initialization.
So ideally I would do like this
public void onCreate(Bundle sis) {
getImagesFromServer(); // API Call
initialzeLists()
initializeAdapters()
}
public View onCreateView(LayoutInflater i, ViewGroup c,Bundle sis) {
recyclerView = findViewById()
setUpAdapters()
return rootView;
}
But if you really want onCreate()
to be called once then reuse Fragment. (Don't create a new instance every time).
While Adding for first time use add it to backStack with a KEY like this
currentFragment = FirstFragment.getInstance();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, currentFragment, "FIRST_KEY")
.addToBackStack("FIRST_KEY")
.commit();
And when you want to add it again get the old instance with the KEY like this
currentFragment = getSupportFragmentManager().findFragmentByTag("FIRST_KEY");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, currentFragment, "FIRST_KEY")
.addToBackStack("FIRST_KEY")
.commit();
Here is the link to a demo project which loads a list of images using the Volley library. It has a similar implementation.
Woof - Use fragments the right way