【问题标题】:how to solve android.os.networkonmainthreadexception [duplicate]如何解决android.os.networkonmainthreadexception [重复]
【发布时间】:2016-12-30 20:53:12
【问题描述】:

我想获取地址中的链接,我使用JsoupRecyclerView,所以我这样做:

public static List<News> newsList(String url) {
    List<News> newsArrayList = new ArrayList<>();
    try {
        Document document = Jsoup.connect().get();
        Elements newsElements = document.select(".boxMiddle .grpLinks a");
        int i = 1;
        for (Element newsElement : newsElements) {
            News news = new News();
            news.setId(i);
            news.setTitle(newsElement.text());
            news.setDate(newsElement.attr("title"));
            news.setUrl(Uri.parse("www.google.com"));
            newsArrayList.add(news);
            i++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return newsArrayList;

}  

但是,我收到此错误:android.os.NetworkOnMainThreadException!

我该如何解决这个错误?

【问题讨论】:

    标签: android jsoup


    【解决方案1】:

    请使用 AsyncTask 。你不能在 UIThread 上进行网络调用。

    https://developer.android.com/reference/android/os/AsyncTask.html

    【讨论】:

      【解决方案2】:

      为您的 I/O 使用 AsyncTask。你不能在主线程上执行网络。

      new AsyncTask<Void, Void, Void>(){
      
        public void doInBackground(Void... params){
          //I/O here
        }
      }.execute();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-22
        • 2021-10-19
        • 2014-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多