Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 233
Hammad Nasir Avatar asked Oct 17 '22 06:10

Hammad Nasir


1 Answers

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.

like image 186
GuilhermeFGL Avatar answered Oct 21 '22 02:10

GuilhermeFGL