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
}
cody
  • 6,389
  • 15
  • 52
  • 77

2 Answers2

14

Should be like this:

Toast toast = Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG);
toast.show();
Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • Hah, that was blindingly obvious. Sometimes we look for the complications in the sea of simplicity. :) – JimR Oct 31 '10 at 19:43
  • 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 footprint – xil3 Jan 12 '11 at 13:48
  • 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. GL – deadfish Apr 05 '12 at 12:07
  • 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 emulator – gilsaints88 Mar 28 '13 at 17:16
11

Yes, I put it right behind the existing line:

Toast.makeText(this, R.string.txt_file_not_found, Toast.LENGTH_LONG).show();
cody
  • 6,389
  • 15
  • 52
  • 77
  • 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 :) – xil3 Jan 12 '11 at 13:46
  • @xil3: I think that @cody accepted the other answer because it solved the problem, but posted his/her own answer just to inform others. – Matt Ball Apr 25 '11 at 04:17