Wednesday, March 28, 2012

Asynchronous Web Service Call in Android Native Application


Recently I was exploring ways of calling a web service asynchronously in Android. I was looking for an option that would work along the lines of XMLHttpRequest AJAX request in Javascript.
Following is one way of doing it
To execute an asynchronous task, Android OS itself provides a class called AsyncTask<Params, Progress, Result> which enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Having said that we can extend the class like  below
public class RemoteCallTask extends AsyncTask<String, Void, ArrayList<String>>
{
RemoteCallListener listener = null;
private final HttpClient httpClient = new DefaultHttpClient();
private String responseText;
public RemoteCallTask(RemoteCallListener listener)
{
this.listener = listener;
}
@Override
protected ArrayList<String> doInBackground(String… urls)
{
ArrayList<String> arrayList;
// Call the webservice and assume the response is JSONArray
// Construct the array list and return
return arrayList;
}
protected void onPostExecute(final ArrayList<String> arrayList)
{
// The returned arraylist in doInBackground() will be sent as an input
parameter here
// Now call the listener’s onRemoteCallComplete method and set the value.
listener.onRemoteCallComplete(arrayList);
}
}
The RemoteCallListener referred in the above code is an interface which looks like below
public interface RemoteCallListener
{
public void onRemoteCallComplete(ArrayList<String> arrayList);
}
Now wherever you need to call the web service do the following things
1) Implement the RemoteCallListener interface.
2) Provide an implementation for onRemoteCallComplete() method.
3) Call the AsyncTask like below
new RemoteCallTask(this).execute(url);
Now the webservice response will be received in onRemoteCallComplete() method.
That’s all.  Please let me know if there is any other better method to achieve this.

No comments:

Post a Comment