Reputation: 50
I need some help to manage fragments and asynctask, I´ve search a lot in google and here in stackoverflow but I didn´t get a positive result.
I have an app with a TabsActivity and three tabs (fragments). One of them is a google maps. I´m trying to update the markers in the map with a get call throw a custom request class.
The problem is that I want to call a function in the fragment map class from the postexecute method. I have the context in the asyntask, I tried also passing the fragment as a parameter but I don´t know even in that way how to call the function. The Asynctask class is a file (it isn´t inside the fragment class).
Any help will be apreciated.
Regards.
P.D - sorry about my poor english :))
Upvotes: 2
Views: 2519
Reputation: 1
I had the same problem. It got solved using a broadcastreceiver. This is how I did it:
class TabsTask extends AsyncTask<String, Void, String> {
static final String BROADCAST_ACTION = "CALL_FUNCTION";
@Override protected String doInBackground(String... params) {
//some statements
}
protected void onPostExecute(String result) {
try {
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
mContext.sendBroadcast(broadcast);
} catch (Exception e) {
//some statement(s)
}
}
}
Now, in your fragment class:
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
function_you_want_to_call();
}
};
public void onResume() {
//other statements
IntentFilter filter = new IntentFilter();
filter.addAction(TabsTask.BROADCAST_ACTION);
activity.registerReceiver(receiver, filter);
}
public void onPause() {
//other statements
activity.unregisterReceiver(receiver);
}
Upvotes: 0
Reputation: 11038
Try passing your fragment to the AsyncTask like this:
class WorkerTask extends AsyncTask<Void, Void, Void> {
private MyMapFragment mapFragment;
WorkerTask(MyMapFragment mapFragment) {
this.mapFragment = mapFragment;
}
@Override
protected Void doInBackground(Void... params)
{
...
}
@Override
protected void onPostExecute(Void res)
{
mapFragment.updateStuff(...);
}
}
Upvotes: 2