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
}
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.
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.
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()
A simpler way to do this is to overwrite the onStop and use getApplicationContext() . Then the toast will appear when the activity closes.
Should be like this:
Toast toast = Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
toast.show();
Yes, I put it right behind the existing line:
Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG).show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With