Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast does not display when used in catch block

I noticed that a toast isn't displayed when it's used inside a catch block. Does anyone know how to show toasts when catching exceptions? An Example:

try {
    // try to open a file
} catch (FileNotFoundException e) {
    Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
    return; // cancel processing
}
like image 432
cody Avatar asked Oct 31 '10 19:10

cody


People also ask

Which method is used to display toast?

Use the makeText() method, which takes the following parameters: The application Context . The text that should appear to the user. The duration that the toast should remain on the screen.

Why is toast not working in Android Studio?

You're trying to display a Toast in a background thread. You should do all your UI operations on the main UI thread. The exception RuntimeException: Can't create handler inside thread that has not called Looper. prepare() can be a little cryptic for beginners but essentially it tells you that you're in a wrong thread.

Can I show toast from background thread?

Steps: declare a handler in the main activity (onCreate) now create a thread from the main activity and pass the Context of that activity. now use this context in the Toast, instead of using getApplicationContext()

How do I show toast in another activity?

A simpler way to do this is to overwrite the onStop and use getApplicationContext() . Then the toast will appear when the activity closes.


2 Answers

Should be like this:

Toast toast = Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
toast.show();
like image 67
Peter Knego Avatar answered Sep 27 '22 20:09

Peter Knego


Yes, I put it right behind the existing line:

Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG).show();
like image 31
cody Avatar answered Sep 27 '22 22:09

cody