Search code examples
javaandroidhandlerrunnableandroid-handler

Android: java.lang.RuntimeException caused by Handler


Good Morning!

I have an android app in the google play store with a widget that load some data from server. In my Play-Console I get the following exception:

java.lang.RuntimeException: 


  at android.os.AsyncTask$3.done (AsyncTask.java:318)

  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:354)

  at java.util.concurrent.FutureTask.setException (FutureTask.java:223)

  at java.util.concurrent.FutureTask.run (FutureTask.java:242)

  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:243)

  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)

  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:607)

  at java.lang.Thread.run (Thread.java:762)


Caused by: java.lang.RuntimeException: 

  at android.os.Handler.<init> (Handler.java:200)

  at android.os.Handler.<init> (Handler.java:114)

  at package.Widget.fehler (Widget.java:279)

  at package.Widget_Server.doInBackground (Widget_Server.java:73)

  at package.Widget_Server.doInBackground (Widget_Server.java:19)

  at android.os.AsyncTask$2.call (AsyncTask.java:304)

  at java.util.concurrent.FutureTask.run (FutureTask.java:237)

The java class "Widget_Server.java" starts a connection and get the datas from server. "Widget.java" is the Main_class for the Widget.

Widget_Server.java, line 73:

finally {
     try {
        reader.close();
     } catch(Exception ex) {
               EXCEPTION (line 73) -> widget.fehler("Fehler! #2215", context);
     }
}

Widget.java, line 279: (inside the method fehler(String, Context))

remoteViews.setTextViewText(R.id.label4, fehlerbeschreibung);

   EXCEPTION (line 279) -> Handler handler = new Handler();
   handler.postDelayed(new Runnable() {
      public void run() {
           remoteViews.setViewVisibility(R.id.loading, View. INVISIBLE);
           update(context);
      }
   }, 1000);

How can the Handler initialisation throw a runtime_exception?

I've searched for a long time but I didn't find information about that.

Thanks for all answers!


Solution

  • Handler handler = new Handler() actually invoke below constructor.

    public Handler(Callback callback, boolean async) {
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
    

    As you see, if Looper.prepare() has not been called, the RuntimeException is threw.