Ori Seri
Ori Seri

Reputation: 967

NetworkOnMainThreadException sometimes thrown

I try to get response from POST request. The problem is that sometimes I get NetworkOnMainThreadException although I'm using AsyncTask for the network communication. That means that sometimes I get the response successfully, and sometimes I get this exception.

Here is my HTTP POST request AsyncTask:

static class HTTPPostRequest extends AsyncTask<PostRequestParams, Void, AsyncResponse> {

    @Override
    protected AsyncResponse doInBackground(PostRequestParams... params) {
        AsyncResponse retVal = new AsyncResponse();
        HttpClient client = getHttpClient();
        UrlEncodedFormEntity formEntity = null;
        HttpPost request = new HttpPost();

        try {
            request.setURI(new URI(params[0].URL));
            formEntity = new UrlEncodedFormEntity(params[0].params);
            request.setEntity(formEntity);

            HttpResponse response = client.execute(request);
            retVal.setOutput(response);

        } catch (ClientProtocolException e) {
            retVal.setException(e);
        } catch (IOException e) {
            retVal.setException(e);
        } catch (URISyntaxException e) {
            retVal.setException(e);
        }

        return retVal;
    }

}

And the code that actually call it:

AsyncResponse response = new AsyncResponse(); 
    PostRequestParams postParams = new PostRequestParams();
    postParams.URL = URL + "login.php";
    postParams.params.add(new BasicNameValuePair("username", username));
    postParams.params.add(new BasicNameValuePair("password", password));

    try {
        response = new HTTPPostRequest().execute(postParams).get();
        if (response.getException() != null) {
            return "Error";
        }
        HttpResponse httpResponse = (HttpResponse) response.getOutput();
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            return "Error " + httpResponse.getStatusLine().getStatusCode();
        }

        return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
    } catch (InterruptedException | ExecutionException | IllegalStateException | IOException e) {
        response.setException(e);
        return null;
    }

Upvotes: 1

Views: 143

Answers (1)

donfuxx
donfuxx

Reputation: 11321

You should move the code that handles the InputStream, like:

 return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));

to your AsyncTask as well. Handling InputStreams is nothing that you want to do in your UI Thread.

Upvotes: 4

Related Questions