Async error “Current thread must have a looper” when clicking retry button

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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.

回答1:

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);     } } 


回答2:

This code worked for me:

new Handler(Looper.getMainLooper()).post(new Runnable() {     @Override     public void run() {         primaryProgressBar.setVisibility(View.GONE);     } });


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!