Reputation: 21573
I have some data to load in an Android Fragment. I need to make a network connection. I am wondering what is the most appropriate method to start loading data. Should it be
onCreateView()
or
onStart()
or
onResume()
?
Thanks!
Upvotes: 4
Views: 1556
Reputation: 8208
I usually do that in onResume()
. I then just use a boolean
to know if I have to fetch data:
if (!dataFetched) {
fetchData();
dataFetched = true;
}
You could anticipate it, but you'll need to check if your views are accessible. If they're not, you have to keep the data and use it in onViewCreated()
:
onCreate() { // or onActivityCreated() if you need Context
fetchData();
}
onViewCreated() {
if (data != null) {
loadDataInViews();
}
}
onNetworkResponseArrived(Data response) { // Method called by the network callback
if(views != null) {
loadDataInViews();
}
else {
data = response;
}
}
Upvotes: 2
Reputation: 12933
IMO onCreate()
is the most appropriate selection. Because this callback is not included in the lifecycle if the Fragment goes to the background and comes to the foreground again. It will only be called if the Fragment is created.
In onCreateView and any following callback you have to determine when you wanna call the network. This will disappear if you choose onCreate().
If the context is needed, onAttach() is the better choice. Because onAttach() will get the Activity as a parameter and is like onCreate() independent of the foreground/background lifecycle.
Upvotes: 4