2016-12-30 26 views
-1

我想在一個地址鏈接,和我用JsoupRecyclerView,所以我這樣做:如何解決android.os.networkonmainthreadexception

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

我該如何解決這個錯誤?

回答

0

使用AsyncTask你的I/O。您無法在主線程上執行聯網。

new AsyncTask<Void, Void, Void>(){ 

    public void doInBackground(Void... params){ 
    //I/O here 
    } 
}.execute(); 
相關問題