Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HTTP requests in Fragment onCreateView, onCreate or onActivityCreated?

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.

like image 390
tsil Avatar asked Nov 10 '22 09:11

tsil


1 Answers

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.

like image 164
Arno van Lieshout Avatar answered Nov 14 '22 23:11

Arno van Lieshout