如何使用AsyncTask修复Android中的NetworkOnMainThreadException

时间:2015-01-13 15:02:17

标签: android android-asynctask networkonmainthread

当我编写此代码时,它提供NetworkOnMainThreadException所以我想使用AsyncTask来实现它虽然我已经看到很多关于此错误的问题和答案,但却无法编写它。我想将一个参数传递给Asynctask类,并希望将返回的数据分配给当前类中的变量。请帮助我。这是我的代码

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    int tem = 1940+position;
    String temp = ""+tem;
    String ReceivedData ="<";
    GettingInternetData something = new GettingInternetData(temp);
    try {
        ReceivedData = something.getMoviesData();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

GettingInternetData.java

public class GettingInternetData {

    String y = null;
    public GettingInternetData(String year) {
        // TODO Auto-generated constructor stub
        y = year;
    }
public String getMoviesData() throws Exception
{
    BufferedReader toRead = null;
    String data = null;
    try
    {
        HttpClient client = new DefaultHttpClient();
        URI url = new URI("URL goes here which requires an argument temp");
        HttpGet getting = new HttpGet();
        getting.setURI(url);
        HttpResponse resp = client.execute(getting);
        toRead = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        StringBuffer alldata = new StringBuffer();
        String l ="";
        String nl = System.getProperty("line.Separator");
        while((l = toRead.readLine()) !=null)
        {
            alldata.append(l + nl);
        }
        toRead.close();
        data = alldata.toString();
        return data;
    }
    finally{
        if (toRead != null){
            try{
                toRead.close();
                return data;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
}
}

先谢谢

3 个答案:

答案 0 :(得分:0)

您希望将参数传递给自定义AsyncTask,让它在doInBackground()方法中完成工作并返回任何结果。然后,您可以使用onPostExecute()方法处理结果。有关AsyncTask的更详细说明,您可能会发现本文有用:http://po.st/Cei3m2

答案 1 :(得分:0)

试试这个

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    new InternetAsynTask().execute(String.valueOf(1940+position));
}

public static class InternetAsynTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        GettingInternetData gettingInternetData = new GettingInternetData(params[0]);
        return gettingInternetData.getMoviesData();
    }

    @Override
    protected void onPostExecute(String s) {
        // TODO:
        // processing receive data here
    }
}

答案 2 :(得分:0)

首先,您不应该通过互联网从您的应用程序主线程调用任何服务获取或发布信息。所以,你可以使用android os提供的asynctask.Also,你告诉过,你想把信息传递给asynctask。我想它会对你有帮助, private class SyncWithServerTask extends AsyncTask<VALUE, Void, String> { protected Long doInBackground(VALUE... values) { int count = valus.length; for (int i = 0; i < count; i++) { publishProgress((int) ((i / (float) count) * 100)); //HERE YOUR CODE // Escape early if cancel() is called if (isCancelled()) break; } return result; }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(String result) {
     showDialog(result);
 }

}

然后,使用,调用您的服务, new SyncWithServerTask().execute(value1, value2, value3);