CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图

时间:2012-11-13 14:09:09

标签: android

我尝试使用线程更改ListView适配器的值,但它抛出了一个CalledFromWrongThreadException异常 任何人都可以调用一个更改任何View元素值的线程吗? 这是我的代码:

new Thread(new Runnable(){

    public void run() 
    {
        ap=(ArrayList<Application>) getBoughtApps(android_id);
        adapter1 = new MyCustomAdapter(ap);
        listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
            changeAdapter();    
    }
}).start();

2 个答案:

答案 0 :(得分:3)

第一个选项:

使用runOnUiThread从非Ui线程更新UI。将您的代码更改为:

new Thread(new Runnable(){

    public void run() 
    {
      ap=(ArrayList<Application>) getBoughtApps(android_id);
       Current_Activity.this.runOnUiThread(new Runnable() {
         public void run() {

           adapter1 = new MyCustomAdapter(ap);
           listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
           changeAdapter(); 
          //Your code here..
         }
       });

    }
}).start();

<小时/> 第二个选项:

您可以使用AsyncTask代替线程进行网络操作,或者应用程序需要从后台更新Ui。您可以使用AsyncTask更改当前代码:

private class CallwebTask extends AsyncTask<Void, Void, String>
{

    protected ArrayList<Application> doInBackground(String... params) 
    {
        ap=(ArrayList<Application>) getBoughtApps(android_id);
        return ap; // Return ArrayList<Application>
    }

    protected onPostExecute(ArrayList<Application> result) {
        Log.i("OnPostExecute :: ", String.valueOf(result.size()));
        //Put UI related code here
        adapter1 = new MyCustomAdapter(result);
        listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
        changeAdapter(); 
    }
}

并开始AsyncTask将此行放在您启动Thread的位置:

new CallwebTask().execute();

答案 1 :(得分:1)

视图只能由UI线程访问。您可以从runonUIThread块

尝试相同的操作
runOnUiThread(new Runnable() {
    public void run() {
          ap=(ArrayList<Application>) getBoughtApps(android_id);
        adapter1 = new MyCustomAdapter(ap);
        listView = ( ListView ) MainActivity.this.findViewById(R.id.listview);
            changeAdapter();   
    }
});