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.
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:
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:onCreate
, initialize all this data (empty container), initialize adapter and then execute theAsyncTask
.onCreateView
, prepare the view to return - adapter etc. So now, onceAsyncTask
will finish, inonPostExecute
it callsyour_adapter.notifyDataSetChanged()
. This will redraw the fragment, since adapter will be informed that data has changed (fetched from the server).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.