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

It seems harder than it sounds, or am I doing it wrong. I need to update the contents of user interface elements in a fragment.

So, in Activity , I run an AsyncTask task like this

 new MyAsyncTask().execute(); 

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

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

This one does not work .

Can anyone help?

PS. My fragments are not <fragment> views in XML, but I deal with them through the ViewPager . I have no problem displaying pages through ViewPager .
PPS this async class parses the remote content and populates the user interface elements in the fragment.

+6
source share
1 answer

This may not solve the problem, but create a method in your fragment and call it to create and run the async task. It will just be more neat. Here is the code.

From Fragment call the method as follows.

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

Or you can try the solution that I have already proposed.

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

Which also works.

+8
source

All Articles