16

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. I have a fragment class MyFragment.java

public class MyFragment extends Fragment {


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

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

        return rootView;
    }

}

I need to know which callback method I have to call webservice to update the UI of fragment. Right Now I am calling web services from onCreateView method. but I need to know what should be best way to call web service from fragment.

Ashish Dwivedi
  • 8,048
  • 5
  • 58
  • 78

3 Answers3

11

If I understand your problem correctly, you want to fetch some data from the server and then inform the fragment that data is prepared and redraw the fragment, is that correct? According to the documentation here:

onCreate() - The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.

onCreateView() The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.

When you create a Fragment somewhere else in your application, onCreate() method is called. When fragment has to be drawn for the first time, onCreateView() is called and this method returns a created View. In your case, you could probably go with something like:

  1. Declare an instance variable (container) for this data and adapter (if you use any).
  2. In onCreate, initialize all this data (empty container), initialize adapter and then execute the AsyncTask.
  3. In onCreateView, prepare the view to return - adapter etc. So now, once AsyncTask will finish, in onPostExecute it calls your_adapter.notifyDataSetChanged(). This will redraw the fragment, since adapter will be informed that data has changed (fetched from the server).
tjurczyk
  • 111
  • 2
1

Depends on when you want to fetch the data. Do you want it every time the app comes to the foreground? Use onResume() Do you want it only when the app starts for the first time? Use onViewCreated(), which gets called after onCreateView is finished.

AndroidDev
  • 1,485
  • 2
  • 18
  • 33
1

onCreate() is tricky.

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;
}

TRICKY PART

But if you really want onCreate() to be called once then reuse Fragment. (Don't create a new instance every time).

How to reuse a Fragment?

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();

Demo project:

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

enter image description here

Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
  • With bottom navigation, all fragments are recreating. In my case, I need to call the API only once. How to achieve this with your approach? – Mac_Play Jan 16 '21 at 09:30
  • You can add a boolean check do like this if(!alreadyLoaded){ yourAPICall(); alreadyLoaded = true } – Rohit Singh Oct 11 '21 at 20:15