-2

I want to save data to DB in new Thread and after that show toast on the UI.

Method for saving:

public void addToBasket(String text) {

        new Thread(() -> {

                //emulate save
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
              //after that I need say ti UI thread - show Toast!
        }).start();
    }

I call this method:

BasketService.me().addToBasket(result.getContents());

I do now want use AsyncTask for this. Please tell me the best way to implement such tasks

ndequeker
  • 7,932
  • 7
  • 61
  • 93
ip696
  • 6,574
  • 12
  • 65
  • 128

2 Answers2

-1

batter to use:

runOnUiThread(new Runnable() {
                public void run() {
                //Do what ever you want do man 
            }
        });

runOnUiThread() method to manipulate your UserInterface from background threads.

ND1010_
  • 3,743
  • 24
  • 41
-1

In case of callback from a nonUi thread to Ui thread you can use runOnUiThread()(As specified above) or Handler. Below is a example of using handler.

 protected static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

protected void onSuccessInMainThread(final R result, final Bundle bundle) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            callback.onSuccess(result, bundle);
        }
    });
}

protected void onErrorInMainThread(final Exception error) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            callback.onError(error);
        }
    });
}
ADM
  • 20,406
  • 11
  • 52
  • 83