I'm trying to open certain apps using there package names and for that I'm using this code:
public void openAppHavingPackageName(String packageName, String appName) {
try {
Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(packageName);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
It is working fine when I'm trying to open the apps which are installed in my phone but when I tried to open an app which is not in my phone, the app crashed giving this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.migrateExtraStreamToClipData()' on a null object reference
on the line
startActivity(intent);
As you can see I have a try/catch
block there then why the exception is not getting caught up and instead the code is getting run causing the crash?
NullPointerException
can not be catch in atry catch
block if it is not inplicited incatch
range. It is a run-time exception, which is recommended to avoid it, instead of dealing in atry catch
block:In your code, to handle the
NullPointerException
exception, you will need to do this:But again, this way is not the recommended.