How to display a Toast inside a Thread on Android?

Asked

Viewed 681 times

4

I’m developing an app and I needed to display a Toast at some point within a Thread, but I’m not getting it, does anyone know how it’s possible and if it’s possible to do so? Thank you in advance.

Note: if it is not a Oast, it could be a Dialog too, but the same problem.

  • Do you have any code already done? Click [Edit] and add to the question for easy analysis.

2 answers

7


The reason is that objects using the UI are not allowed to be accessed, as is the case with Toast, in a Thread other than the Uithread(Mainthread).

In the method run() of Thread use the method runOnUiThread() to place a Runnable in Uithread.

new Thread() {
    public void run() {

        ....
        ....
        runOnUiThread(new Runnable() {

            @Override
            public void run() {

                //Coloque aqui o código que necessita de correr
                //na UI thread, como por exemplo o Toast
            }
        });

    }
}.start();

Note: The same applies if you are an Asynctask and wish to use Toast on doInBackground().

  • It worked perfectly as I needed it. Fight!

4

I think what you need is to call Toast.makeTexts from UI Thread, inside your thread you can do so:

activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Sou um toast dentro de uma thread", Toast.LENGTH_SHORT).show();
  }
}); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.