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?

1

There are 1 answers

0
GuilhermeFGL On

NullPointerException can not be catch in a try catch block if it is not inplicited in catch range. It is a run-time exception, which is recommended to avoid it, instead of dealing in a try catch block:

if(something != null) {
   doStuff();
}

In your code, to handle the NullPointerException exception, you will need to do this:

try {
    Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(packageName);
    startActivity(intent);
} catch (ActivityNotFoundException | NullPointerException e) {
    Log.e(TAG, e.getMessage());
}

But again, this way is not the recommended.