It turns out that when I want to show a message by Toast and send 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
for getApplicationContext()
it no longer throws me an error, but when I run the application and execute this method the application closes....
The strange thing is that when I replace it Toask.makeText
with a System.out.println(string) it works perfectly for me and it obtains the data I need from the Database.
If you define as context
this
to create theToast
, the problem is that the context will try to be the Thread itself, it is recommended in this case to use the application context through getApplicationContext() .You can also use the context of the
Activity
in case you have access:but it's lighter to use getApplicationContext() .
There are several ways to display a
Toast
during the execution of aThread
, for example using aHandler
or usingrunOnUiThread()
. As an example:With this you will have no problem displaying the
Toast
during the execution of aThread
.Good.
I think your solution is to run the toast inside the Ui Thread, like this:
According to the runOnUiThread documentation :
In Spanish :
Your code should look something like this: