如何从另一个线程访问UI对象?

时间:2011-09-10 19:52:48

标签: android multithreading thread-safety

我有一个包含ListView的活动。当我想从另一个线程访问此ListView时,我收到此错误..

我该怎么做?

错误日志:

09-10 18:48:48.502: ERROR/ClientActivity(455): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.ViewRoot.focusableViewAvailable(ViewRoot.java:1712)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:452)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:452)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:452)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:452)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.View.setFlags(View.java:4614)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.view.View.setFocusableInTouchMode(View.java:3190)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.widget.AdapterView.checkFocus(AdapterView.java:694)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.widget.AdapterView$AdapterDataSetObserver.onChanged(AdapterView.java:789)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:31)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.widget.BaseAdapter.notifyDataSetChanged(BaseAdapter.java:50)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at android.widget.ArrayAdapter.notifyDataSetChanged(ArrayAdapter.java:247)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at socket.android.ClientActivity$ClientThread.run(ClientActivity.java:100)
09-10 18:48:48.502: ERROR/ClientActivity(455):     at java.lang.Thread.run(Thread.java:1019)

1 个答案:

答案 0 :(得分:1)

如果要从其他线程访问小部件,标准方法是使用Handler

here您可以找到如何使用Handler

的示例