gpt4 book ai didi

android.view.ViewRootImpl$CalledFromWrongThreadException

转载 作者:行者123 更新时间:2023-11-29 21:13:42 25 4
gpt4 key购买 nike

我在 ListView 中显示了网页下载百分比的进度条。

for(int i=0;i< 5;i++)
{
new UploadTask(i).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "http://www.google.com");
}

我的上传任务

public class UploadTask extends AsyncTask<String, Void, String>
{
int id;
public UploadTask(int id) {
this.id = id;
}
@Override
protected String doInBackground(String... params) {
try {
return HttpUrlConnection.getContentFromUrl(params[0], listener);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
HttpListener listener = new HttpListener() {

@Override
public void processCompletion(int x) {
publishProgress(x);
}
};
public void publishProgress(Integer... ints) {
progressLevelList.set(id, ints[0]);
uploadAdapter.notifyDataSetChanged();
}
}

但是当我通知适配器时出现以下错误。

java.lang.RuntimeException: An error occured while executing doInBackground()

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

如何解决这个错误?

最佳答案

您不能在后台线程上更改 UI。尝试使用 onProgressUpdate(Object... values) AsyncTask 方法,它在 UI 线程上触发。

@Override
protected void onPreExecute() {
super.onPreExecute();
//do you bg work here

publishProgress(null);

//do you bg work here
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
//update UI here
}

您的代码应如下所示:

  public class UploadTask extends AsyncTask<String, Integer, String>
{
int id;
public UploadTask(int id) {
this.id = id;
}
@Override
protected String doInBackground(String... params) {
try {
return HttpUrlConnection.getContentFromUrl(params[0], listener);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
HttpListener listener = new HttpListener() {

@Override
public void processCompletion(int x) {
publishProgress(x);
}
};

@Override
protected void onProgressUpdate(Integer... values) {
progressLevelList.set(id, ints[0]);
uploadAdapter.notifyDataSetChanged();
}

}

关于android.view.ViewRootImpl$CalledFromWrongThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22016005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com