Asyntask类中的Android NetworkOnMainThreadException

时间:2015-07-01 08:08:08

标签: android exception networkonmainthread

此代码在到达get语句时显示异常(在代码上注释行)。 代码是下一个,包括从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){

}

}

这是从主代码中调用的:

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;
}

我认为它必须是一个愚蠢的失败,但我无法找到错误。感谢。

2 个答案:

答案 0 :(得分:0)

listaComentarios = du.doInBackground(params);

您可以通过调用execute()在后​​台线程中提交执行异步任务,而不是直接调用当前线程中的doInBackground()回调。

将结果传回onPostExecute()中的UI线程。

答案 1 :(得分:0)

因为您致电du.doInBackground(params);

您应该致电du.excute(params)而不是