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

async/await
await in catch block javascript
javascript async error handling
async/await throw error
async call
async/await error handling best practices
unhandled promise rejection async/await
async/await without try/catch

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.

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

Async/await, We can catch such errors using a global unhandledrejection event handler as described in the chapter Error handling with promises. async/await� Assume you want to write some backend using node/express. That’s the good idea, it’s easy — you just write and that’s all you need to start. Then you realize that any backend is usually a queue of…

This code worked for me:

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

Error handling with Async/Await in JS | by Ian Segers, We had a look at simple error handling with and without errors. Let's have a look now at some special cases. Returning from an async function. Using Async/await in Express 25th Sep 2019. Have you noticed you write a lot of asynchronous code in Express request handlers? This is normal because you need to communicate with the database, the file system, and other APIs.

For those who are still looking for answers and are using RxJava for async operations, this might be helpful.

When using Rxjava if you don't specify the observing thread then this error will come.

Caused by: java.lang.IllegalStateException: The current thread must have a looper!

so don't forget to add

subscribeOn(Schedulers.io())

observeOn(AndroidSchedulers.mainThread()) //required

 disposableObserver = Observable.timer(2000, TimeUnit.MICROSECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    //some code
                }
            });

Better error handling with async/await - DEV, This article is intended to suggest a better way to handle errors when using async /await syntax. Prior knowledge of how promises work is� If you are awaiting an asynchronous function, a try..catch block will work. In this case the try..catch block is treated as if it were adding a Promise#catch function.) You ultimately have to catch errors from an async function using the normal Promise#catch method or with the second argument to Promise#then:

Async Await Error Handling in JavaScript, try/catch also handles synchronous errors. run(); async function run() { const v = null;� Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Common Mistakes in JavaScript Async Function Error Handling, Learn JavaScript Async Function Error Handling, and don't throw an error like a normal synchronous function. Error handling is important in� But at the top level of the code, when we’re outside any async function, we’re syntactically unable to use await, so it’s a normal practice to add .then/catch to handle the final result or falling-through error, like in the line (*) of the example above.

How to write async await without try-catch blocks in Javascript, Since async functions are waiting for Promises, when a promise encounters an error it throws an exception that will be catched inside a catch� An async function is a function declared with the async keyword. Async functions are instances of the AsyncFunction constructor, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

Comments
  • What is the code running in the beginning of the doInBackground method showLoadingPage()? It seems like you're trying to make UI manipulations in an Async Task, instead of wating to achieve the mutation in onPostExecute().
  • Can't believe I overlooked that! It's weird that it still worked the first time this task was ran, just not when I used the retry button. Not really sure why I'm getting down votes on my question, but thank you for the answer. That was it!
  • @DuckyDisciple I have the similar problem in the past. When views are created - only main thread can change it contents (sometimes people calls it UI Thread). onPreExecute method is called on ui thread and views can be updated. But doInBackground is not calling on ui thread and you have getting the exception if views are created and rendered. Always update ui in ui thread.
  • Also make sure you specify the non IO/Computation operations that is the UI operations after the observeOn(AndroidSchedulers.mainThread()) like so: .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe(...) .doOnComplete(...) .subscribe(...)