Right Approach to Call Web Service(API) from Fragment class

Dwivedi Ji picture Dwivedi Ji · Apr 28, 2014 · Viewed 8k times · Source

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.

Answer

tjurczyk picture tjurczyk · Apr 28, 2014

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).