null pointer
null pointer

Reputation: 5914

android cancel previous http get request

I want to create an autoCompleteTextview with the suggestion from the web-service. On text change I call the web service with the text entered.

public String searchpalace_Searchtext(String serchtext)  
{       
    String resultString = "";   
    try {           
        String searchtext = URLEncoder.encode(String.valueOf(serchtext), "UTF-8");              
        HttpClient Clientloc = new DefaultHttpClient();         
        String URL = baseUrl + "places?name=" + searchtext;      
        HttpGet httpget = new HttpGet(URL);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        resultString = Clientloc.execute(httpget, responseHandler);             
    }
    catch (Exception e) {
        resultString = "";
    }     

    return resultString;
}

This function is called from the asyncTask when reach character is entered or deleted. Now when the text is entered fast the I want to cancel the pending request when the new request is arrived. How can I cancel the previous request?

Upvotes: 0

Views: 884

Answers (3)

NeilS
NeilS

Reputation: 635

If HttpClient.execute() can be interrupted, AsyncTask.cancel(true) will do it if you pass (true). The docs don't say if it's interruptable or not, experiment. If it doesn't then you may need to investigate the toolkit suggested in another answer. Anyway you can check isCancelled() and not apply the result. Probably not a huge overhead once the connection has been started.

Note that, depending on Android version, sometimes multiple AsyncTasks can run in parallel (donut - honecomb) and sometimes they only run one at a time and queue up (honeycomb onwards). You can change the thread executor to allow them to run in parallel, see the AsyncTask class docs, but this will affect the rest of your app too.

Also note you're not allowed to re-use an AsyncTask once it's been run.

Upvotes: 0

Ramesh
Ramesh

Reputation: 54

You can use Android volley network tool kid for cancel the HttpRequest,

Upvotes: 0

Deepak Bala
Deepak Bala

Reputation: 11185

You can go through each queued task and call the cancel() method. Check if the task was cancelled using isCancelled(). Do not trigger async tasks for every change in the text box. You can introduce a small delay to avoid unnecessary creation of AsyncTask objects.

Upvotes: 1

Related Questions