In my app , I need to use startActivity to see the content of the file , or use the default application to open the certain file , but sometimes the android system may not i
If you want to display error as toast then
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// TODO: handle exception
//Show Toast...
}
The error occurs because the activity not mentioned in the manifest file.
<activity android:name=".yourActivity"
android:label="@string/app_name">
</activity>
I think your question is more: "how can I catch a certain exception and prevent a force crash". This is how you do it in code:
try {
// here is your code that can potentially throw the exception and the force crash
} catch (ActivityNotFoundException activityNotFound) {
Toast.makeText(this, "your error message", Toast.LENGTH_SHORT).show();
// maybe also log the exception, for future debugging?
}
A warning, don't abuse this: it's dangerous to "silently swallow" exceptions and can make your application unstable and introduce weird and hard-to-debug behaviour.
You can use resolveActivity
method
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}else {
Toast.makeText(this,"No suitable app found!",Toast.LENGTH_SHORT).show();
}
Just simply add that activity in your manifest file..
like,
<activity android:name=".ActivityName"
android:label="@string/app_name">
</activity>
EDIT:
Now to catch the ActivityNOtFoundException
put your code in,
try {
// Your startActivity code wich throws exception
} catch (ActivityNotFoundException activityNotFound) {
// Now, You can catch the exception here and do what you want
}
Note: Be careful when you catch this ActivityNotFound Exception but you can't modified manifest file to run time, means once you encountered the exception and if you want to add that this activity tag at runtime then you can't.