Skip to content
Fix Code Error

Can’t create handler inside thread that has not called Looper.prepare()

March 13, 2021 by Code Error
Posted By: Anonymous

What does the following exception mean; how can I fix it?

This is the code:

Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);

This is the exception:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
     at android.os.Handler.<init>(Handler.java:121)
     at android.widget.Toast.<init>(Toast.java:68)
     at android.widget.Toast.makeText(Toast.java:231)

Solution

You’re calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example.

Look up Communicating with the UI Thread in the documentation. In a nutshell:

// Set this up in the UI thread.

mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message message) {
        // This is where you do your work in the UI thread.
        // Your worker tells you in the message what to do.
    }
};

void workerThread() {
    // And this is how you call it from the worker thread:
    Message message = mHandler.obtainMessage(command, parameter);
    message.sendToTarget();
}

Other options:

You could use an AsyncTask, that works well for most things running in the background. It has hooks that you can call to indicate the progress, and when it’s done.

You could also use Activity.runOnUiThread().

Answered By: Anonymous

Related Articles

  • Error inflating class android.support.v7.widget.Toolbar?
  • Restful API service
  • Unable to run Robolectric and Espresso with a…
  • Error in styles_base.xml file - android app - No…
  • Eclipse will not start and I haven't changed anything
  • Android app unable to start activity componentinfo
  • How to add Typescript to a Nativescript-Vue project?
  • Android : Fragment doesn't fit into Fragment Container
  • ListView inside ScrollView is not scrolling on Android
  • MaterialCardView is in front of NavigationView. How…
  • How to set dropdown arrow in spinner?
  • android.view.InflateException: Binary XML file line…
  • Android Layout Animations from bottom to top and top…
  • What is the purpose of Looper and how to use it?
  • Data binding parent-child relationships in Aurelia
  • AppCompat v7 r21 returning error in values.xml?
  • Integrate ZXing in Android Studio
  • java.lang.NullPointerException: Attempt to invoke…
  • onBillingSetupFinished never called
  • How to use worker_threads on Sapper?
  • How to implement HorizontalScrollView like Gallery?
  • Getting duplicated cardviews using SwipeRefresh Layout
  • Layout doesn't expand more than initial size it was…
  • SecurityException: Permission denied (missing…
  • Android Room - simple select query - Cannot access…
  • Changing Icon Color behind ListTile in an…
  • Google in-app billing, a toast breaks everything
  • java.lang.RuntimeException: Unable to start activity…
  • recyclerview opens wrong item after filtering list…
  • firebase storage java.lang.IllegalStateException:…
  • Proper implementation of web workers in Aurelia and…
  • READ_EXTERNAL_STORAGE permission for Android
  • Fragment Not Showing in the Activity
  • Android:java.lang.OutOfMemoryError: Failed to…
  • Split dataframe to different days
  • onClick for buttons on custom CardView
  • Strange out of memory issue while loading an image…
  • Failed to load AppCompat ActionBar with unknown…
  • What's the relationship between kernel object and…
  • Button is null object reference (Android Studio)
  • Remove Text from the edit text when edit text is focused
  • Constraint Layout Vertical Align Center
  • VueJS service-worker.js is ignored in my PWA
  • Android "gps requires ACCESS_FINE_LOCATION" error,…
  • Vue js vuecli3 application does not work in ie11…
  • Center crop scale type not working in android image view
  • Neither BindingResult nor plain target object for…
  • java.lang.IllegalStateException: Can not perform…
  • Android App crashes on animated gradient background
  • TLS 1.3 server socket with Java 11 and self-signed…
  • GridLayout and Row/Column Span Woe
  • Vue Cli 3 how to use the official PWA plugin (…
  • Playing HTML5 video on fullscreen in android webview
  • How to get current location in Android
  • How can I manually compile a svelte component down…
  • Error inflating class…
  • Android getting value from selected radiobutton
  • Google Maps Android API v2 - Interactive InfoWindow…
  • android.content.res.Resources$NotFoundException:…
  • Email and phone Number Validation in android
  • Android ListView headers
  • Item position in RecyclerView only changing when…
  • Android adding simple animations while…
  • How to pass values between Fragments
  • Good way of getting the user's location in Android
  • Navigation View and Constraint Layout
  • Can't create handler inside thread which has not…
  • Duplicate ID, tag null, or parent id with another…
  • Access service worker skipWaiting from within App…
  • Unable to move from one fragment to another
  • Calculate the mean by group
  • Why doesn't catching Exception catch RuntimeException?
  • Android + Pair devices via bluetooth programmatically
  • Java Android Check if e-mail already exists on firebase
  • Reference — What does this symbol mean in PHP?
  • Android Studio : java.lang.NullPointerException:…
  • How to use ScrollView in Android?
  • Login button need to be clicked twice in order to login
  • Percentage width in a RelativeLayout
  • Android - How to download a file from a webserver
  • Refresh cache on App update not working - Vue,…
  • Make display data textviews invisible until a city…
  • Worker Script Failing to Load for Vue Webpack Built App
  • What to do on TransactionTooLargeException
  • How to center the content inside a linear layout?
  • Couldn't load memtrack module Logcat Error
  • How can I handle a click event in Listview?
  • How to convert image into byte array and byte array…
  • Unable to display translated text on text view
  • Android- Error:Execution failed for task…
  • Use worker-loader with vue-cli and webpack
  • Is there an addHeaderView equivalent for RecyclerView?
  • RxJava Main Thread Always Crash
  • How to get the current location latitude and…
  • App keeps stopping, logcat error not understandable
  • NullPointerException: Attempt to invoke virtual…
  • Throw HttpResponseException or return…
  • SVG Mask is "bleeding" on canvas edges
  • Can't access Eclipse marketplace
  • not getting the desired result in ExecutorService

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Stop and Start a service via batch or cmd file?

Next Post:

How to enumerate an enum

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error