Reputation: 21
First and foremost:
*I have Fragment classes which serve as a class for each page in the viewPager.
*Each fragment class has its own AsyncTask
.
My problem here is that the AsyncTask
's of each fragment class are called at once when the class that has the ViewPager
is called. I know because in each of the AsyncTask
's onPreExecute()
i put a ProgressDialog
. I am expecting that every time I swipe and go to another page, that should be time when the AsyncTask
of each of the fragment class will load, not on the first page all at once.
I tried putting the AsyncTask.execute()
on the onActivityCreated(Bundle)
but still nothing changes.
Also, every time I swipe pages, the ProgressDialog
inside the AsyncTask
's onPreExecute() shows up. I placed a Log in every onPreExecute() but surprisingly it prints one time only ever since the
viewPager` is called.
Upvotes: 0
Views: 392
Reputation: 448
If you want each AsyncTask
started only when your Fragment
is visible, you must execute it from either the Fragment
's onStart()
or onResume()
method. The reason they're all being called at the same time is because a Fragment
's onActivityCreated()
is called when the parent Activity
is created, not when the Fragment
is visible. Take a look at the lifecycle of a Fragment
to see when it would be most appropriate to execute your AsyncTask
.
Additionally, since you are using Fragments, I would highly suggest using a Loader
as opposed to an AsyncTask
. They are much easier to manage alongside of a Fragment
.
Upvotes: 1