Skip to content Skip to sidebar Skip to footer

Update Ui Through Handler

I need to update my UI from an external Thread. I can't use runOnUiThread, because it's an application using StandOut libraries. So I created my Handler in the class containing met

Solution 1:

You need not extend all Handler class if you just want to handle some messages, just implement Handler.Callback:

privatefinalclassUICallbackimplementsHandler.Callback{
    publicstaticfinalintDISPLAY_UI_TOAST=0;
    privatestaticfinalintLOAD_PROFILE=1;

    @OverridepublicbooleanhandleMessage(Message msg) {
        switch (msg.what) {
            case UICallback.DISPLAY_UI_TOAST: {
                Contextcontext= mw.getApplicationContext();
                Toastt= Toast.makeText(context, (String) msg.obj,
                        Toast.LENGTH_SHORT);
                t.show();
                returntrue;
            }
            case UICallback.LOAD_PROFILE:{
                loadProfile((String) msg.obj);
                returntrue;
            }
            default:
                returnfalse;
        }
    }
}

Note, in above code, true is returned when message is handled, false when message was not meant for us.

Now, create a handler with main looper (so that all messages run on UI thread ), and the callback we created:

Handlerhandler=newHandler(Looper.getMainLooper(),newUICallback());

Solution 2:

Refer below links you can get some ideas...

Android: got CalledFromWrongThreadException in onPostExecute() - How could it be?

Android CalledFromWrongThreadException

Can't resolve CalledFromWrongThreadException with Handler

CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch views

Handler changing UI causes CalledFromWrongThreadException

Post a Comment for "Update Ui Through Handler"