top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Android: Handle the asynchronous callback

+1 vote
355 views

I want to handle asynchronous callback/handler by executing in the sequence I request. The actual request is WebClient request. Please suggest how can I accomplish this?

posted Sep 27, 2016 by Vijay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

To run asynchronous you should extend the class to separate AsyncTask. You could use the code below,

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

Then initiate request using new RequestTask().execute("<REQUEST_URL>");

Make sure you have added this permission, <uses-permission android:name="android.permission.INTERNET" />

answer Oct 2, 2016 by Vinod Kumar K V
...