只能在主线程更新ui,或者用handler传输。爬虫是在另一个异步线程进行,所以爬出来的数据对控件赋值就比较麻烦。这次使用了线程数据传到runnable将数据传到handler进行赋值。
结果图:
源码:
String word="软件工程"; // textView.setText(content.text().toString());//将爬取到的内容给另一个页面赋值 class MyRunnable implements Runnable { @Override public void run() { try{ Document doc = (Document) Jsoup.connect("https://baike.baidu.com/item/"+word).get(); Element content = doc.select("div.para").first(); // String title = doc.title(); //String title = doc.title(); con=content.text().toString(); Message message=new Message(); message.obj=con; }catch(java.io.IOException e) { e.printStackTrace(); } // TODO Auto-generated method stub System.out.println("马佳慧"+con); Message msg = new Message(); Bundle bundle = new Bundle(); bundle.putString("name", con); msg.setData(bundle); handler.sendMessage(msg); } Handler handler = new Handler() { public void handleMessage(Message msg) { TextView textView = ( TextView) findViewById(R.id.textView1); Bundle b = new Bundle(); b = msg.getData(); System.out.println(b.get("name")+"测试数据"); textView.setText(b.get("name").toString()); } }; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(activity_main); new Thread(new MyRunnable()).start(); }