Search code examples
androidexceptionnetworkonmainthread

Android NetworkOnMainThreadException inside Asyntask class


This code shows the exception when it reach the get sentence (line commented on the code). The code is the next, consist on get a comments list from Http get Request:

public class ObtencionComentariosPerfil extends AsyncTask<String, Integer, List<Comment>>{

@Override
protected List<Comment> doInBackground(String... params) {
    // TODO Auto-generated method stub
    HttpClient httpClient = new DefaultHttpClient();
    URI url;
    List<Comment> listaComentarios = new ArrayList<Comment>();

    try {
        url = new URI(params[1]);
        HttpGet del = new HttpGet(url);
        del.setHeader("content-type", "application/json");
        del.setHeader("X-Auth-Token", params[0]);
        System.out.println("El token params es: "+params[0]);

        HttpResponse resp = httpClient.execute(del);// THE EXCEPTION shows here
        StatusLine estatus = resp.getStatusLine(); 

        if (estatus.getStatusCode() == 200) {
            InputStream is = resp.getEntity().getContent();
            CommentsParser parser= new CommentsParser();
            listaComentarios = parser.parseoComentarios(is.toString());
        } else {
            System.out.println("Error");
            listaComentarios = null;
        }


    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return listaComentarios;
}
@Override
protected void onPostExecute(List<Comment> lista){

}

}

Here is called from main code:

public List<Comment> obtieneComentariosPerfil(long idUsuario, String aut){
    List<Comment> listaComentarios = new ArrayList<Comment>();
    String url= "http://"+ip+":8080/api/users/"+idUsuario+"/comments";
    String[] params= new String[2];
    params[0]=aut;
    params[1]=url;
    ObtencionComentariosPerfil du = new ObtencionComentariosPerfil();
    listaComentarios = du.doInBackground(params);

    return listaComentarios;
}

I think it have to be a stupid failure but i cant find the error. Thanks.


Solution

  • Because you call du.doInBackground(params);

    you should call du.excute(params) instead