Skip to content Skip to sidebar Skip to footer

Call Inner Asynctask From Outside Fragment

I have an inner AsyncTask which i have call from a fragment outside the fragment which contains this AsyncTask. I have read and saw some examples where they use an interface. I can

Solution 1:

You can use a decoupled messaging system as EventBus or Otto. First fragment will be publisher and second subscriber. In the latter you'll start the AsyncTask.

Later on you can use the system anywhere in the app whenever you need to send an object from one component to another.

Solution 2:

Simply move the AsyncTask into its own public class and you can call it from wherever you like. Have a callback interface and implement that in the fragments where you are calling the AsyncTask.

Solution 3:

Create an interface for the Fragment class

publicinterfaceOnFragmentButtonListener{
    onMyButtonClicked();
}

Now, have your activity hosting these fragments implement this interface.

In your OnClick method, have that call

((OnFragmentButtonListener)getActivity()).onMyButtonClicked();

Next create a method inside your Fragment Class hosting the AsyncTask inner class.

publicvoidstartAsyncTask(){
    new LoadQueueTask.execute();
}

Inside the activity, you are forced to implement your interface method onMyButtonClicked(); In this method, get a handle to your fragment and call the startAsyncTask method in the fragment.

Post a Comment for "Call Inner Asynctask From Outside Fragment"