There are multiple ways of doing this but one of my favourite ways is with a callback interface.
Here is the JSONTransmitter:
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
private OnJsonTransmitionCompleted mCallback;
public JSONTransmitter(OnJsonTransmitionCompleted callback) {
this.mCallback = callback;
}
@Override
protected JSONObject doInBackground(JSONObject... data) {
//.....
return json;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
this.mCallback.onTransmitionCompleted(jsonObject);
}
public interface OnJsonTransmitionCompleted {
void onTransmitionCompleted(JSONObject jsonObject);
}
}
The callback interface OnJsonTransmitionCompleted
is inside the JSONTrasnmitter
as its only use is with the JSONTransmitter
.
Here is the main activity:
public class SupportMapActivity extends Activity implements JSONTransmitter.OnJsonTransmitionCompleted{
public void sync(View v){
LocationsDB mLocationsDB = new LocationsDB(SupportMapActivity.this);
Cursor events= mLocationsDB.getAllLocations();
try {
JSONObject json = makJsonObject(events);
JSONTransmitter transmitter = new JSONTransmitter(this);
transmitter.execute(new JSONObject[]{json});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onTransmitionCompleted(JSONObject jsonObject) {
// Now you have access to your JSON data in your activity!
}
}
So we create a callback interface inside the JSONTransmitter
which has one method void onTransmitionCompleted(JSONObject jsonObject)
that will pass the JSONObject
to your activity from onPostExecute(JSONObject jsonObject)
.
Inside the main activity we implement JSONTransmitter.OnJsonTransmitionCompleted
and pass in this
when we instantiate JSONTransmitter
and lastly we Override void onTransmitionCompleted(JSONObject jsonObject)
inside the activity and once our AsyncTask
has finished its background process and onPostExecute(JSONObject jsonObject)
has been called we will receive the JSONObject
inside the implemented method onTransmitionCompleted(JSONObject jsonObject)
.
I hope this helps here are a few links on this topic:
android asynctask sending callbacks to ui
http://android-er.blogspot.co.il/2013/09/implement-callback-function-with.html
http://blog.redkitmedia.com/android-asynctask-sending-callbacks-to-ui/
http://android-dwivediji.blogspot.co.il/2014/01/best-way-to-use-asynctask-class.html