0

我尝试使用线程更改 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();
4

2 回答 2

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您可以使用as更改当前代码:

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将这一行放在开始线程的位置:

new CallwebTask().execute();

于 2012-11-13T14:13:06.737 回答
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();   
    }
});
于 2012-11-13T14:12:55.267 回答