I use the interface as a delegate for this. Here is an example:
In my main activity, I have an onClick listener to start my asynchronous call and a listener to handle after the call ends.
private void enableLocationButton(){ locationButton = (Button) findViewById(R.id.locationButton); locationButton.setEnabled(true); locationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, selectLocationActivity.class); intent.putExtra("serverURL",server.getWebServerAddressField()); startActivityForResult(intent, 200); } }); } @Override protected void onActivityResult(int requestCode,int resultCode, Intent data){ if(resultCode == RESULT_OK) { switch (requestCode){ case 100: processServerResponse((PmsWebServer) data.getBundleExtra("server").get("server")); break; case 200: processLocationResponse((PmsDataSource)data.getBundleExtra("location").get("location")); default:processError(); } }else{ processError(); } }
Somewhere in selectLocationActivity I have an Async call invocation and something to handle the response, note that this class implements the interface that is used in the Async invocation.
public class selectLocationActivity extends ListActivity implements SoapServiceInterface{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_location_select); chosenServer = this.removeURLHeader(getIntent().getStringExtra("serverURL")); this.retrieveLocationOptionsByServer(chosenServer); } private void retrieveLocationOptionsByServer(String server) { Map<String,Object> parms = new HashMap<String,Object>(); parms.put(WEB_SERVER_NAME,server); SoapServiceObject service = new SoapServiceObject(Services.SERVICE_DETAILS,parms); callTheService(service); } private void callTheService(SoapServiceObject service){ SoapServiceHelper helper = new SoapServiceHelper(); helper.delegate = thisActivity; helper.execute(service); } @Override public void serviceCallComplete(SoapObject response){ this.createClickableListOnScreen(response); }
serviceCallComplete is started by asyncTask. Below is the code for this task.
public class SoapServiceHelper extends AsyncTask<SoapServiceObject, Void, SoapObject>{ public SoapServiceInterface delegate = null; private Integer RETRY_COUNT = 0; private final Integer MAX_RETRY_COUNT = 2; protected SoapObject doInBackground(SoapServiceObject... args){ SoapServiceObject service = args[0]; try{ service.callTheService(); }catch(Exception e){ System.out.println("An error occurred calling the service\n" + e.getMessage()); } return service.getResponse();
And finally, here is the interface
public interface SoapServiceInterface { public void serviceCallComplete(SoapObject response); }
I know that I show something on the screen directly from my result, I simply substitute this part with saving and reading;)