android - 调用Asynctask调用webservice后如何更新listview

标签 android android-asynctask

我调用 webservice通过asynctask , 调用 webservice我正在调用一个名为 makeRequest() 的方法在doInBackground() , 我正在用另一种方法得到响应 success() ,在成功方法中,我正在更新 listview

但是我遇到了这样的错误

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

我在这里添加我的代码。我正在调用 synctask来自 Activity

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.

帮我解决这个问题...

最佳答案

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

Activity_name.this.runOnUiThread(new Runnable() {

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

关于android - 调用Asynctask调用webservice后如何更新listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6922561/

相关文章:

Android Thread、AsyncTask 与从 BLE onCharacteristicChanged() 调用的 IntentService

android - 从脚本加载不同的查看器配置文件

android - 在android中创建数据库文件

java - Android 计算器崩溃

Android:无法从线程内访问 View

AsyncTask 类中的 Android Intent 给出错误

java - Recyclerview 和 Rest Api

android - 如何将 asynctask onpostexecute 方法的结果传递给父 Activity android

android - 如何从多个通知android中识别选定的通知?

java - Android HttpURLConnection 错误