App crashing with 'boolean android.content.Intent.migrateExtraStreamToClipData()' on a null object reference' even when try/catch block is there [duplicate]
S

1

7

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?

Softboiled answered 6/9, 2017 at 12:56 Comment(0)
E
4

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.

Economical answered 6/9, 2017 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.