简体   繁体   中英

Getting Null Pointer Exception on method getIntent().getCategories()

The following code is causing Getting Null Pointer Exception on method 'boolean java.util.Set.contains(java.lang.Object)' Null Pointer Exception.I suspect

getIntent().getCategories().contains(Intent.CATEGORY_LAUNCHER)

is causing the problem.

Some of the users are reporting it's crashing when they're opening app from Home Screen . But It doesn't crash while opening from Playstore Open Button

Couldn't reproduce the issue on any of my devices but getting tons of crashes on Crashlytics. Any Idea what's happening?

private boolean hasPendingIntent() {
        return getIntent() != null && getIntent().getCategories().contains(Intent.CATEGORY_LAUNCHER) && getIntent().getData() != null;
    }

This code block is not null safe. Because, before checking a set is null or not null, you are trying to fetch data from it.

It is not necessarily an intent must have one or more categories according to this statemment. For more follow the link .

An intent with no categories always passes this test, regardless of what categories are declared in the filter.

You need to check, Is getIntent().getCategories() null or not null first? After that, you should check, is it contains Intent.CATEGORY_LAUNCHER .

getIntent()  != null && 
getIntent().getCategories() != null && getIntent().getCategories().contains(Intent.CATEGORY_LAUNCHER) && 
getIntent().getData()

You should check for null categories in getIntent().getCategories(); eg: if(getIntent().= null && getIntenger().getCategories() !=null) {}

This will workaround the nullpointer. You may need to verify for empty categories list to preserve the current logic.

add null point check before use, try to change the code below:

    private boolean hasPendingIntent() {
        boolean b = false;
        if (getIntent() != null && getIntent().getCategories() != null && getIntent().getData() != null) {
            b = getIntent().getCategories().contains(Intent.CATEGORY_LAUNCHER);
        }
        return b;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM