Search code examples
javaandroidandroid-asynctasknetworkonmainthread

Network error on main thread, while using AsyncTask


I am trying to build my first android app, it uses AsyncTask to execute a post request. (to log into a website).

I got the app working fine with StrictMode turned off, but i would like it to be error free when executed in StrictMode also. Eventhough I redesigned my app using AsyncTask it still gives me this error:

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)

From what I have read on the internet, using AsyncTask should have solved this. I don't want to use Java Threads because i want to learn to do it the correct way.

I build a new class to execute the task, it's called MyAsyncTask, here is de class code

<code>
package com.am.tuto;
import android.os.AsyncTask;// removed rest of imports for readability
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
String u;
String p;

public MyAsyncTask(String u, String p)
{
    this.u=u;
    this.p=p;
}

@Override protected String doInBackground(Void... params) {
String msg="";
if ((u.length()>0)&&(p.length()>0))
{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://irrationalgamers.com/test.php");
try 
{
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("username", u));
    nameValuePairs.add(new BasicNameValuePair("password", p));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response =httpclient.execute(httppost); // <----the error occurs
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    msg="success";
    msg=responseString;
} 

catch (ClientProtocolException e) 
{
// TODO Auto-generated catch block
} 
catch (IOException e) 
{
// TODO Auto-generated catch block
}  
}
else
{
   msg="failed";
}
return msg;
}

@Override protected void onPostExecute(String result) 
{
    MyBus.getInstance().post(new AsyncTaskResultEvent(doInBackground()));
}
}
</code>

I am thinking that it might be because i created my own constructor, but i feel I really have to pass it some parameters.

I can continue programming the app, but it would be nice to learn how to prevent this issue in the future. Every article i read on the error points me to AsyncTask, it's hard to find a solution for when already implemented...

Any thoughts on this would be highly aprreciated


Solution

  • Basically, ρяσѕρєя K answered your question. Some extra details: you should never call doInBackground yourself. The whole point of AsyncTask is that it manages passing the work to the background worker thread and returning the results to the UI thread. What doInBackground returns is what onPostExecute receives as a parameter.

    Your onPostExecute should look like this:

    @Override
    protected void onPostExecute(String result) {
        MyBus.getInstance().post(new AsyncTaskResultEvent(result));
    }