我正在研究jsoup库,我已经编写了这个简单的代码来观察它是如何工作的:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadThread.start();
}
Thread downloadThread = new Thread() {
@Override
public void run() {
TextView tw = (TextView) findViewById(R.text_view.tw1);
Document doc;
try {
doc = Jsoup.connect("http://www.google.it").get();
tw.setText(doc.title());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
我已将此元素添加到AndroidManifest.xml
<uses-permission
android:name="android.permission.INTERNET"/>
但是当我启动软件时,我有后续错误:
04-27 17:25:49.801: E/AndroidRuntime(26035): FATAL EXCEPTION: Thread-2004
04-27 17:25:49.801: E/AndroidRuntime(26035):
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that
created a view hierarchy can touch its views.
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:854)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.view.ViewGroup.invalidateChild(ViewGroup.java:4075)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.view.View.invalidate(View.java:10386)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.view.View.invalidate(View.java:10341)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.widget.TextView.checkForRelayout(TextView.java:6439)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.widget.TextView.setText(TextView.java:3696)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.widget.TextView.setText(TextView.java:3554)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
android.widget.TextView.setText(TextView.java:3529)
04-27 17:25:49.801: E/AndroidRuntime(26035): at
com.example.webparsingtest.MainActivity$1.run(MainActivity.java:30)
答案 0 :(得分:2)
您无法从与主线程不同的线程访问UI组件。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ExampleAsyncTask().execute();
}
static class ExampleAsyncTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... unused) {
Document doc;
try {
doc = Jsoup.connect("http://www.google.it").get();
return doc.title();
} catch (IOException e) {
return null;
}
}
@Override
protected void onPostExecute(String title) {
if(title == null){
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
return;
}
TextView tw = (TextView) findViewById(R.text_view.tw1);
tw.setText(title);
}
}
}