How to display a message with Toast within a Thread in Android Studio?

2

It turns out that when I want to show a message through Toast and send it the context I get an error, I do it like this:

 public void mostrarMascotas(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Connection con = new Conexion().getConexion();
                Statement stm = con.createStatement();
                ResultSet rs = stm.executeQuery("SELECT * FROM tbl_mascota");
                String cadena = "";
                while (rs.next()){
                    cadena += rs.getString("mascota_nombre")+"\n";
                }
                Toast.makeText(this, cadena, Toast.LENGTH_LONG).show();// Aqui me sale el error
            }
            catch (Exception exp) {
                System.out.println("Error al conectarse con la BD: "+ exp.getMessage());
            }
        }
    }).start();
}

in the Toast when changing the context this by getApplicationContext() no longer throws me an error, but when running the application and I execute this method the application is closed ....

The strange thing is that replacing the Toask.makeText with a System.out.println (string) works perfectly for me and gets me the data I need from the Database.

    
asked by Alexis Rodriguez 24.04.2017 в 22:18
source

2 answers

4

If you define as context this to create the Toast , the problem is that the context will try to be Thread itself, it is recommended in this case to use the context of the application using getApplicationContext () .

// Toast.makeText(this, cadena, Toast.LENGTH_LONG).show();// Aqui me sale el error
Toast.makeText(getApplicationContext(), cadena, Toast.LENGTH_LONG).show();
  

getApplicationContext () : Returns the context of the object   Unique global application of the current process.

You can also use the context of Activity in case you have access:

Toast.makeText(MainActivity.this,cadena, Toast.LENGTH_LONG).show();

but it's lighter to use getApplicationContext () .

  

How to display a message with Toask within a Thread on Android   Studio?

There are several ways to display a Toast during the execution of a Thread , for example, using a Handler or using runOnUiThread() . As an example:

   runOnUiThread(new Runnable() {
                        public void run() {
                           //Toast.makeText(this, cadena, Toast.LENGTH_LONG).show();// Aqui me sale el error     
                           Toast.makeText(getApplicationContext(),cadena, Toast.LENGTH_LONG).show();
                        }
                    });

With this you will have no problem showing the Toast during the execution of a Thread .

answered by 25.04.2017 / 01:36
source
1

Good morning.

I think your solution is to run the toast in Ui's Thread, in the following way:

miActividad.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(miActividad, cadena, Toast.LENGTH_SHORT).show();
    }
});

According to the documentation of runOnUiThread :

  

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the thread, the action is posted to the queue event of the UI thread.

In Spanish:

  

Executes the action specified in the user interface thread. If the current thread is the UI thread, the action executes immediately. If the current thread is not the UI thread, the action is located in the event queue of the UI thread.

Your code should look something like this:

public void mostrarMascotas(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                /** operaciones */
                ClaseActividad.this.runOnUiThread(new Runnable() {
                    public void run() {
                       Toast.makeText(miActividad, cadena, Toast.LENGTH_SHORT).show();
                   }
                });
            }
            catch (Exception exp) {
                System.out.println("Error al conectarse con la BD: "+ exp.getMessage());
            }
        }
    }).start();
}
    
answered by 24.04.2017 в 22:28