Question

Earlier I was using Default Http client of android and then found this library at http://loopj.com/android-async-http/

When I use this library inside doInBackground(String... args) of AsyncTask, I noticed that postExecute() finished before android-async-http returned.

Should I not use AsyncTask if I'm using AsyncHttpClient. If I only use AsyncHttpClient, is there way to handle timeouts on slow internet connection or internet access.

I'm new to android, please help!

Was it helpful?

Solution

As implied by the above library you can make network calls asynchronously i.e. not on the main thread and that is why we actualy use asynctask to avoid blocking the main thread.

So , if you are using the above library then there is no need to use Asynctask and I am sure you will never get NetworkConnectionOnMainThreadException. Hope this helps.

OTHER TIPS

If you use this library you don't have to use the AsyncTask class for requests.

Inside your Activity code you can just put something like this:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});

This will send the request automatically in a background thread. Inside onSuccess you can deal with the response (similar to onPostExecute but I guess it is not on the UI Thread).

With AsyncHttpClient, you can easily handle time-outs via a statement like this:

client.setTimeout(5000)

Check the library docs for all available methods.

First of all asynctask is a synchornous execution and AsyncHttpClient is a simultaneous execution. Don't use client inside asynctask. Use only AsyncHttpclient like this. Create common request handler and listener. You can also create different request methods like makeRequest for each request you want, and also create different listeners.

public class RequestHandler{

private static RequestHandler instance;

private AsyncHttpClient client;

private RequestHandler(){
    client = new AsyncHttpClient();
}

public static RequestHandler getInstance(){
    if(instance == null){
        instance = new RequestHandler();
    }
    return instance;
}

// You can add more parameters if you need here.
public void makeRequest(String url, RequestListener listener){
    client.get(url, new AsyncHttpResponseHandler() {

        @Override
        public void onStart() {
            // called before request is started
            //Some debugging code here
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            listener.onSuccess(statusCode, headers, response);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable exception) {
             listener.onFailure(statusCode, headers, errorResponse,exception);
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
            //Some debugging code here, show retry dialog, feedback etc. 
        }

        @Override
        public void onRetry(int retryNo) {
             //Some debugging code here-------

        }
    });
 }
}

public interface RequestListener{
public void onSuccess(int statusCode, Header[] headers, byte[] response);
public void onFailure(int statusCode, Header[] headers, byte errorResponse, Throwable e);
}

Give this request url like this from activity or fragment

RequestHandler handler = RequestHandler.getInstance();
handler.makeRequest("http://www.google.com", new RequestListener(){
 @Override
 public void onSuccess(int statusCode, Header[] headers, byte[] response) {
    // do whatever you want here.       
 }
});

Use async-http-client only and just set the timeouts in this way:

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

public MyClassConstructor(){

    asyncHttpClient.setConnectTimeout(5000); // default is 10 seconds, minimum is 1 second
    asyncHttpClient.setResponseTimeout(5000); // as above
    asyncHttpClient.setTimeout(5000); // both connection and socket timeout
    asyncHttpClient.setMaxRetriesAndTimeout(1, 100); // times, delay

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top