如何解决android.os.networkonmainthreadexception
我想在地址中获取链接,我使用如何解决android.os.networkonmainthreadexception,android,jsoup,Android,Jsoup,我想在地址中获取链接,我使用Jsoup和RecyclerView,所以我这样做: public static List<News> newsList(String url) { List<News> newsArrayList = new ArrayList<>(); try { Document document = Jsoup.connect().get(); Elements newsElements =
Jsoup
和RecyclerView
,所以我这样做:
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;
}
公共静态列表新闻列表(字符串url){
List newsArrayList=新建ArrayList();
试一试{
Document Document=Jsoup.connect().get();
Elements newsElements=document.select(“.boxMiddle.grpLinks a”);
int i=1;
for(新闻元素:新闻元素){
新闻=新新闻();
新闻,setId(i),;
news.setTitle(newelement.text());
news.setDate(newelement.attr(“title”);
news.setUrl(Uri.parse(“www.google.com”);
newsaraylist.add(新闻);
i++;
}
}捕获(IOE异常){
e、 printStackTrace();
}
返回newsArrayList;
}
但是,我得到了这个错误:android.os.NetworkOnMainThreadException
如何解决此错误?请使用AsyncTask。无法在UIThread上进行网络调用
对I/O使用
AsyncTask
。无法在主线程上执行联网
new AsyncTask<Void, Void, Void>(){
public void doInBackground(Void... params){
//I/O here
}
}.execute();
newasynctask(){
公共void doInBackground(void…params){
//此处输入/输出
}
}.execute();