Toast does not display when used in catch block
Asked Answered
A

2

8

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
}
Alcoholic answered 31/10, 2010 at 19:27 Comment(2)
Does it appear if you sleep for 2 seconds before the return statement?Selfsown
No.. I tried and it didn't change anything. Nothing happens...Alcoholic
O
14

Should be like this:

Toast toast = Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
toast.show();
Outbid answered 31/10, 2010 at 19:41 Comment(4)
Hah, that was blindingly obvious. Sometimes we look for the complications in the sea of simplicity. :)Selfsown
This works but not sure why it was selected as the best answer. Why are you passing the static toast to a non static object if all you're going to do is just show it? Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG).show(); <-- this would of worked just fine and with less of a memory footprintAdo
For people whom it doesn't work, toast can sometimes don't show when you use it in emulator, whem you test your project on own android phone it works fine. Check another topic about "toast" and "emulator" there is a problem with service. GLBunyan
I am also using toast in my actual Nexus S device and sometimes it also doesn't show and I don't know why. So it's not just in the emulatorDilan
A
11

Yes, I put it right behind the existing line:

Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG).show();
Alcoholic answered 31/10, 2010 at 19:55 Comment(2)
Not sure why that other answer got accepted as the best - this was clearly the most logical way to do it. Unless you're doing other things to the Toast, there is no need to pass the static one to another object and then use that to show... Anyways, I gave you +1 for what I thought was the best answer for this given question :)Ado
@xil3: I think that @Alcoholic accepted the other answer because it solved the problem, but posted his/her own answer just to inform others.Samaria

© 2022 - 2024 — McMap. All rights reserved.