Skip to content Skip to sidebar Skip to footer

Android : Cancelling Progressbar Caught Exception : Android.view.viewroot$calledfromwrongthreadexception

I am trying to implement a progressbar in my application. This progressbar is visible on button click, and then a thread is also starting along with it. when the thread completes,

Solution 1:

You should call it from UI thread:

runOnUiThread(new Runnable() {
        publicvoidrun() {
             progressbar.setVisibility(View.GONE);
        }
    });

Another approach is to use AsyncTask instead of regular Thread.

Solution 2:

you have to call it with a runnable

staticHandlerhandler=newHandler();
...

handler.post(hideprogress);


...

staticRunnablehideprogress=newRunnable()
    {
        @Overridepublicvoidrun() {
            progressbar.setVisibility(View.GONE);
        }
    };

Solution 3:

You can use a Handler to hide the progress bar:

privatestaticfinalintHANDLER_MESSAGE_UPDATE_COMPLETE=0;

ThreadthredUpdate=newThread()
{
    publicvoidrun()
    {
        ClearDatabase();
            Messagemsg= Message.obtain();
            msg.what = HANDLER_MESSAGE_UPDATE_COMPLETE;
            myHandler.sendMessage(msg);                                          
    }
};

HandlermyHandler=newHandler() {
    @OverridepublicvoidhandleMessage(Message msg) {
        switch(msg.what){
        case HANDLER_MESSAGE_UPDATE_COMPLETE:
            progressbar.setVisibility(View.GONE);
            break;
        default:
            Log.w("MY_TAG","message type not supported: " + msg.what);
        }
    }
};

This approach gives you the flexibility of being able to easily add new message types to handle future changes. It also keeps all your UI updates in one place for easier maintenance.

Post a Comment for "Android : Cancelling Progressbar Caught Exception : Android.view.viewroot$calledfromwrongthreadexception"