With the error Cordova-> Looper.prepare ()

I often get angry with Thread while using Cordova.framework, so I'll take a note of myself with a commandment.

error contents

adb.logcat


java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

It happens when you create a View in a background thread.

Cause

Cordova isn't basically because it uses a Web engine, but ... there are times when I have to use NativeView, so that's when.

For example

test.Java


@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            ...
            timerView = view.findViewById(R.id.hogeview);

            //No good point! !! !!
            mHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mRootView.addView(timerView);
                },200);
            }
        }
    });
    return true;
}

This is an example of what I did because View generation was heavy + screen transition was sandwiched. Further delay processing is written in the thread processing of cordova. Looper basically runs on the UI thread, so if you change the thread with Handler, Looper will not work.

Since the creation of View is heavy this time, it is called by cordova.getActivity (). RunOnUiThread (), so mHandler (). PostDelayed (new Runnable () { Will get rid of.

Easy solution

test.Java


@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            ...
            timerView = view.findViewById(R.id.hogeview);
            mRootView.addView(timerView);
        }
    });
    return true;
}

Or there is a way to implement Looper yourself. However, basically, it is a method called by Framework, so it is forbidden.

I often do such simple things ...

Recommended Posts

With the error Cordova-> Looper.prepare ()
Change the port with SpringBoot
Mock the constructor with PowerMock
Error when playing with java
Error with db: migrate: reset
How to deal with the error ERROR: While executing gem ... (Gem :: FilePermissionError)
Monitor the clipboard with JNA
[Rails] What was the error message?
Simulate the simplex method with GUI
Automatically scroll the background with libGDX
Programming with ruby (on the way)
[Error] SassC :: SyntaxError with background-image: image-url
Follow the link with Selenium (Java)
Place in the middle with css
DB error on deploying with Heroku
The guy who tries-with-resources with kotlin
Image processing: Let's play with the image