Nitesh Yadav
Nitesh Yadav

Reputation: 49

Android HTTP Request Making App Irresponsive

I want to make a simple HTTP Head Request to URL which is fetched from a text box. Everytime I enter the URL and Click to get the HTTP response, the App Become Irrespnosive. Here is the code :

public  void    MakeRequest(View v)
{
    EditText mEdit;
    TextView txtresponse;
    txtresponse = (TextView)findViewById(R.id.textView1);
    mEdit = (EditText)findViewById(R.id.editText1);
    HttpClient httpClient = new DefaultHttpClient();
    HttpHead httphead = new HttpHead(mEdit.getText().toString());

    try {
        HttpResponse response = httpClient.execute(httphead);
        txtresponse.setText(response.toString());
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();

    }
}

Upvotes: 0

Views: 197

Answers (2)

rnk
rnk

Reputation: 2549

Never perform long running tasks on the UI Thread (and HTTP Request / Response can take very long due to server latency). Run the HTTP handling in a background thread. There are several examples on Stackoverflow - like Make an HTTP request with android and of course read up on Android site - http://developer.android.com/training/articles/perf-anr.html

Upvotes: 1

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

You are probably doing the request in the UI thread. This is bad practice, as it is in charge of all work done for the UI. You can read more about this here.

A better way would be to do this in another thread. This can be done with e.g.

Example with an AsyncTask (this goes inside your class):

public void MakeRequest(View v)
{
    EditText mEdit;
    mEdit = (EditText)findViewById(R.id.editText1);
    new RequestTask().execute(mEdit.getText().toString());
}

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

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpHead httphead = new HttpHead(params[0]);

        try {
            HttpResponse response = httpClient.execute(httphead);
            return response.toString();
        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onPostExecute(String result) {
        TextView txtresponse;
        txtresponse = (TextView)findViewById(R.id.textView1);
        txtresponse.setText(result);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

Upvotes: 0

Related Questions