5

I use Navigation Tabs in my app. I have 3 fragments which load different data from Internet. I want to know the best place where to put the code that make the HTTP request, in onCreate, onCreateView or onActivityCreated?

Usually, I put all the code (requesting data, populating adapter, inflating view...) in onCreateView. I also saw many people doing it on Internet.

But this guide https://github.com/thecodepath/android_guides/wiki/Creating-and-Using-Fragments do things differently. So I want to be sure on what to do exactly.

tsil
  • 2,069
  • 7
  • 29
  • 43

2 Answers2

1

I would normally put the code to refresh the view with new states in the onResume(). I would only inflate the view in onCreateView and possibly set adapters and such.

It also depends on how fresh you want the data. I you only need to load it when the user starts the app, I would load it in the onCreate of the Activity and then load all data for the fragments in one batch. You can then store the data and retrieve it in the different fragments.

Also you always want to load data from the internet on a different thread. If you are set on loading the data in the fragment itself, I would start an asynctask in the onCreate and refresh the view for the fragment in the callbacks from the asyntask. In the onCreateView you can put default values, or let the user know the data is comming via text or some other notification.

If you want real fresh data you can start the asynctask in onResume() of the fragment.

Arno van Lieshout
  • 1,570
  • 1
  • 13
  • 19
0

Answering really late, but if you are making HTTP Requests, I would suggest putting them in onActivityCreated(). onCreateView is great for initialising and binding your views. onActivityCreated is called once this is done and onCreateView returns, as you can see in the answers to this SO question.

You can read more about this here and here on SO.

kilokahn
  • 1,136
  • 2
  • 18
  • 38