0

Previous I haved that AsyncTask on main activity and called with:

new SyncGetLocations(ActivityMain.this).execute();

Now,I move it to a fragment and don't know now how to call it from MainActivity.

AsyncTask look alike :

private static class SyncGetLocations extends AsyncTask<Void, Void, Void> {

    private WeakReference<ActivityMap> activityReference;

    SyncGetLocations(ActivityMap context) {
        activityReference = new WeakReference<>(context);
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected Void doInBackground(Void... voids) {
    }

    @Override
    protected void onPostExecute(Void aVoid) {

    }

}

Viral Patel
  • 1,296
  • 1
  • 11
  • 24

2 Answers2

0

Either

From MainActivity find your fragment:

val fragment = getSupportFragmentManager().findFragmentByTag(...) or findFragmentByID(...)

and then call a method in this fragment to launch the asyncTask

fragent.callAsyncTask()

Or

make your asynctask public or remove it from fragment to be its own class and call it froim every where you want

I suggest you to make asyntask not an inner class of fragment of activity it you wants to call it from everywhere

SebastienRieu
  • 1,443
  • 2
  • 10
  • 20
0

Try attaching Listener to your fragment with a method like

public interface FragmentInteractionListener{ 
void onClick(); 

}

In your fragment

private FragmentInteractionListener fragmentListener;

@Override
public void onDetach() {
    super.onDetach();
    fragmentListener = null;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof FragmentInteractionListener) {
        fragmentListener = (FragmentInteractionListener) context;
    }  else {
        throw new RuntimeException(context.toString()
                + " must implement FragmentInteractionListener");
    }
}

And under onClick event call it like this

fragmentListener.onClick();

Then in your activity implement the FragmentInteractionListener

OR

 ((SomeActivity)getActivity()).someMethod();
GSutey
  • 136
  • 6