سؤال

I'm building an application and am getting a NetworkOnMainThreadException INSIDE an 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'm very confused why this exception is thrown in the do in the doInBackground of an AsyncTask, any ideas?

هل كانت مفيدة؟

المحلول

Move the JSON code into 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);
    ...
}

نصائح أخرى

result.getEntity().getContent() opens a stream that reads from the network, so the network communication IS in the main thread. Move the JSON parsing to doInBackground() and do only the UI tasks in onPostExecute().

I think the problem occurs since your are inheriting the MainActivity into your AsyncTask, try to reomve this part of code:

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

Since you dont need it, and if you want to pass any arguments to the AsyncTask you can pass it through the doInBackGround() method immediatliy.

Also to call your AsyncTask use the following new POST().execute();

Also you don't need to call super.onPostExecute(result); into your onPostExecute() method.

I hope this help.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top