如何在调用Asynctask调用webservice后更新listview

时间:2011-08-03 06:37:21

标签: android android-asynctask

我正在呼叫webserviceasynctask,呼叫webservice我在makeRequest()呼叫一个名为doInBackground()的方法,我收到回复在另一种方法success()中,在成功方法中,我正在更新listview

但是我得到了像

这样的错误
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."

我在这里添加了我的代码。我从活动中调用synctask

new MyTask(this,urlAsString,sp).execute(); 

这里是Asynctask类

class MyTask extends AsyncTask<Void, Void, Void> {
        ProgressDialog progress;

        String url;
        SharedPreferences sp;
        HomepageH2desk c;
          public MyTask(HomepageH2desk context,String url,SharedPreferences sp) {
            this.c = context;
            this.url = url;
            this.sp = sp;
            progress = new ProgressDialog(this.c);
            progress.setMessage("Loading...");
          }

          public void onPreExecute() {
            progress.show();
          }

          public Void doInBackground(Void... unused) {
             c.getTickets(url,sp);
            return null;
            //progress.setMessage("Loading...");
          }

          public void onPostExecute(Void unused) {
            progress.dismiss();
          }
        }

此处即可获得webservice回复

 public void success(Object result) {

     list = (ArrayList<Map<String, String>>) result;

    this.adapter.setList(list);
            this.adapter.notifyDataSetChanged();
}

listview未获得更新并显示错误

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

帮我解决这个问题...

3 个答案:

答案 0 :(得分:19)

您应该像这样更新您的列表。

Activity_name.this.runOnUiThread(new Runnable() {

@Override
public void run() {
      list = (ArrayList<Map<String, String>>) result;
      this.adapter.setList(list);
      this.adapter.notifyDataSetChanged();
    }
});

答案 1 :(得分:5)

因为这是在另一个线程中执行一些MainThread任务时出现的错误.....

试试这个:

runOnUiThread(new Runnable(){

public void run(){

     this.adapter.setList(list);
     this.adapter.notifyDataSetChanged();
   }

});

此代码可能有一些错误但是在简单的单词中..将notifyDataSetChanged调用添加到runOnUiThread()方法中。你将完成..

或者这也可以是DOne(完美的方式)

在您的活动类

中添加以下内容
 private Handler handler = new Handler() {
     @Override
     public void handleMessage(Message msg) {

        this.adapter.setList(list);
        adapter.setnotifyDataSetChanged();
     }
  };

调用此处理程序,以便在何时何地调用notifydatasetchanged,如此

  handler.sendEmptyMessage(0);

由于 沙

答案 2 :(得分:4)

在onPostExecute方法

上调用success方法