Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute AsyncTask<> located in a fragment from its parent?

This seems harder than it look or I am doing it wrong. I need to update the content of UI elements in a fragment.

So, within an Activity, I start AsyncTask task like this

new MyAsyncTask().execute();

Inside "normal" Activity this async class is private so I thought that I could make it public inside the fragment class and then be able to call it from FragmentActivity parent class. Something like this:

MyFragment myFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.layout.my_fragment);
new myFragment.DoParsingAsyncTask().execute(""); //??? a silly guess

This did not work.

Can anyone help?

PS. My fragments are not <fragment> views in XML, but I deal with them via ViewPager. I have no problem displaying pages via ViewPager.
PPS. this async class starts parsing remote content and fill UI elements in the fragment.

like image 262
sandalone Avatar asked Dec 15 '12 13:12

sandalone


1 Answers

It might not solve the problem, but create a method in your fragment and call that to create and start the async task. It will just be tidier. Here is the code.

From Fragment call the method like this.

Activity myActivity = getActivity();
if (myActivity instanceof MyActivity) {
     ((MyActivity) myActivity).doAsyncTaskMethod();
}

Or you can try the solution I've already proposed.

MyFragment myFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.layout.my_fragment);
myFragment.new DoParsingAsyncTask().execute("");

Which works as well.

like image 196
Philip Pearl Avatar answered Oct 21 '22 08:10

Philip Pearl