【问题标题】:How to fix NetworkOnMainThreadException in Android by using AsyncTask如何使用 AsyncTask 在 Android 中修复 NetworkOnMainThreadException
【发布时间】:2015-03-11 13:58:26
【问题描述】:

当我编写这段代码时,它给出了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();
            }
        }
}
}

提前致谢

【问题讨论】:

  • 可怕的问题,许多其他类似问题的重复,但这次你说“我知道我必须使用 AsyncTask”但你没有展示你在使用它时尝试了什么,这是更糟糕...

标签: android android-asynctask networkonmainthread


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      【解决方案3】:

      首先,您不应该从您的应用程序主线程调用任何通过互联网获取或发布信息的服务。所以,你可以使用android os提供的asynctask。另外,你告诉过,你想将信息传递给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);

      【讨论】:

        猜你喜欢
        • 2013-11-13
        • 2012-11-16
        • 2015-01-01
        • 2012-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        • 1970-01-01
        相关资源
        最近更新 更多