异步错误"当前线程必须有一个活套"点击重试按钮时 [英] Async error "Current thread must have a looper" when clicking retry button
问题描述
我有一个应用程序从一个网站读取一些数据,然后对什么是从网站中检索创建 TextViews
。我有这个过程通过的AsyncTask
工作。我知道了建立,因此如果在试图从网站看网络错误,会显示一个重试按钮。我的code完美的作品时,它贯穿于第一次,但是当我尝试从按钮的的onClick
的code,我得到以下错误:
I have an app that reads some data from a website and then creates TextViews
for what is retrieved from the website. I have the process working through an AsyncTask
. I've got it set up so that if there is a network error while trying to read from the website, a Retry button is shown. My code works perfect when it runs through the first time, but when I try to run the code from the onClick
of the button, I get the following error:
java.lang.RuntimeException: An error occured while executing doInBackground()
(a few lines of error code)
Caused by: java.lang.IllegalStateException: The current thread must have a looper!
我什至有的onClick
调用外部方法,我看到有人建议,但是这并没有帮助。下面是一些相关的code的:
I even tried to have the onClick
call an outside method as I saw someone recommend, but that didn't help. Here is some of the relevant code:
异步任务
private class DownloadListingTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls){
showLoadingPage();
try{
return getList(urls[0]);
}
catch (IOException e){
return sharedPreferences.getString("list_cache", "");
}
}
@Override
protected void onPostExecute(String result){
formatList(result);
}
}
调用方法
private void tryDownload(){
DownloadListingTask downloadListingTask = new DownloadListingTask();
downloadListingTask.execute(url);
}
onClick事件
retryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tryDownload();
}
});
所以,当 tryDownload()
方法是从 onCreateView
称它工作得很好,但是当我尝试从在的onClick
是当我得到这个错误。
So when the tryDownload()
method is called from onCreateView
it works fine, but when I try it from the onClick
is when I get that error.
推荐答案
试图调用showLoadingPage在preExecute方式:
Try to call showLoadingPage in onPreExecute method:
private class DownloadListingTask extends AsyncTask<String, Void, String>{
@Override
protected void onPreExecute(){
showLoadingPage();
}
@Override
protected String doInBackground(String... urls){
try{
return getList(urls[0]);
}
catch (IOException e){
return sharedPreferences.getString("list_cache", "");
}
}
@Override
protected void onPostExecute(String result){
formatList(result);
}
}
这篇关于异步错误&QUOT;当前线程必须有一个活套&QUOT;点击重试按钮时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!