Android.os.NetworkOnMainThreadException inside AsyncTask

I create an application and get NetworkOnMainThreadException INSIDE asyncTask

Call:

new POST(this).execute("");

AsyncTask:

public class POST extends AsyncTask<String, Integer, HttpResponse>{
private MainActivity form;
public POST(MainActivity form){
    this.form = form;
}


@Override
protected HttpResponse doInBackground(String... params) {
try {
        HttpPost httppost = new HttpPost("http://diarwe.com:8080/account/login");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
    nameValuePairs.add(new BasicNameValuePair("email",((EditText)form.findViewById(R.id.in_email)).getText().toString()));
    //add more...
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    return new DefaultHttpClient().execute(httppost);
} catch (Exception e) {
    Log.e("BackgroundError", e.toString());
}
return null;
}

@Override
protected void onPostExecute(HttpResponse result) {
super.onPostExecute(result);
try {
    Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
} catch (Exception e) {
    Log.e("BackgroundError", e.toString());
}
}
}

LogCat:

BackgroundError | android.os.NetworkOnMainThreadException

I am very confused why this exception is thrown in doInBackground for AsyncTask, any ideas?

+5
source share
3 answers

Move the code JSONto doInBackground():

@Override
protected HttpResponse doInBackground(String... params) {
    ...
    Your current HttpPost code...
    ...
    Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
    ...
}
+7
source

result.getEntity().getContent()opens a stream that is read from the network, so the IS network connection is in the main stream. Move the JSON parsing to doInBackground()and do only the user interface tasks in onPostExecute().

+2
source

, , MainActivity AsyncTask, :

private MainActivity form;
public POST(MainActivity form){
    this.form = form;
}

Since you do not need this, and if you want to pass any arguments to AsyncTask, you can pass it through the method doInBackGround()immediately.

Also AsyncTaskuse the following to callnew POST().execute();

Also you do not need to call super.onPostExecute(result);into your method onPostExecute().

I hope this help.

0
source

All Articles