Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast is crashing Application, even inside thread

Tags:

android

toast

I have an onClick event in my android app that triggers the following code but it keeps crashing my app. I put it in a thread only because i read that that's supposed to prevent crashing. Also ctx refers to the Activity's context (it's a variable I created in the activity set equal to this. I've read and tried several things. Any help would be awesome. Thanks!

Thread toastThread = new Thread() {
  public void run() {
    Toast alertFailure = Toast.makeText(ctx, "Login Failed", Toast.LENGTH_LONG);
    alertFailure.show();
  }
};
toastThread.start();
like image 794
Hyrum Hammon Avatar asked Jul 01 '13 17:07

Hyrum Hammon


1 Answers

You need to use runOnUiThread

Something like

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

Toast is a UI element so it needs to run on the UI Thread, not a background Thread.

However, if this is all you are using it for then you don't need a separate Thread just to show a Toast. If you can explain the context of how you are using it then maybe we can help with a better way. Also, if you are inside of your Activity then you don't need a variable for Context. You can use ActivityName.this instead to access the Activity Context

like image 152
codeMagic Avatar answered Nov 15 '22 14:11

codeMagic