Android Update UI from background thread

Some time we need to perform some heavy task which can't be run on main ui thread.
To solve this problem we use threads , async task.

If we want to update the UI from background thread, simple way to achieve this is to user runOnUiThread.

below is the code which call sweet alert from the background thread

appCompatActivity.runOnUiThread(new Runnable() {
    @Override    public void run() {
        new SweetAlertDialog(appCompatActivity, SweetAlertDialog.ERROR_TYPE)
                .setTitleText("Oops...")
                .setContentText(error)
                .show();
    }
});






To start the background thread.

new Thread(new Runnable() {
    @Override    public void run() {

        uiAlerts.UIshowProgress();
        try {
           
            uiAlerts.UIhideProgress();
            uiAlerts.UIshowSuccess("Data sucessfully synced");

        }catch (Exception e)
        {

            uiAlerts.UIhideProgress();
            uiAlerts.UIshowError("Sync fail please try again");
            e.printStackTrace();
        }


    }
}).start();

Comments