I have this piece of code, which is not working as expected :
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_feedback: {
try {
Intent intent_email = new Intent(Intent.ACTION_SEND);
intent_email.putExtra(Intent.EXTRA_EMAIL, new String[]{"feedback@xyz.com"});
intent_email.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
intent_email.setType("message/rfc822");
startActivity(intent_email);
return true;
} catch (Exception e) {
Toast.makeText(getBaseContext(), "No Mail app found", Toast.LENGTH_SHORT).show();
}
}
case R.id.action_rate: {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + getPackageName())));
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "No Market app found", Toast.LENGTH_SHORT).show();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
The problem with this code is that when there's an Exception in case R.id.action_rate:
it shows a Toast as No Market app found but when the Exception is in case R.id.action_feedback:
it shows two Toasts, first No Mail app found & then No Market app found . Means it goes in both the catch blocks. Can anyone please explain how is it working like this ?
However, I have made my code working by putting the try
block before switch
statement and putting the catch block after the switch
statement is closed. But still I don't know how the thing is going in this ?
Thanks in Advance :)
You are not breaking out of each case. Try using a "break" after each case.
You should always add break;
in each case
You have to put a break;
right after your first catch block. You may also need to rework your return statements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.