Issue
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!
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:
Async Task
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);
}
}
Calling method
private void tryDownload(){
DownloadListingTask downloadListingTask = new DownloadListingTask();
downloadListingTask.execute(url);
}
onClick event
retryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tryDownload();
}
});
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.
Solution
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);
}
}
Answered By - krystian71115
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.