java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.lang.Iterable.iterator()' when starting a notification

casolorz picture casolorz · Mar 30, 2017 · Viewed 9.8k times · Source

I noticed some of my users are getting this exception. I don't know how to reproduce it, I only have the reports on Crashlytics. Seems to be deep inside Google's code. Out of thousands who have used this code only 39 have had the exception.

Any idea what might be wrong?

Fatal Exception: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.lang.Iterable.iterator()' on a null object reference
       at android.app.ApplicationPackageManager.getUserIfProfile(ApplicationPackageManager.java:2141)
       at android.app.ApplicationPackageManager.getUserBadgeForDensity(ApplicationPackageManager.java:997)
       at android.app.Notification$Builder.getProfileBadgeDrawable(Notification.java:2877)
       at android.app.Notification$Builder.hasThreeLines(Notification.java:3092)
       at android.app.Notification$Builder.build(Notification.java:3646)
       at android.support.v4.app.NotificationCompatApi21$Builder.build(NotificationCompatApi21.java:136)
       at android.support.v7.app.NotificationCompat$LollipopExtender.build(NotificationCompat.java:504)
       at android.support.v4.app.NotificationCompat$NotificationCompatImplApi21.build(NotificationCompat.java:835)
       at android.support.v4.app.NotificationCompat$Builder.build(NotificationCompat.java:1752)
       at mycode.startNotification(mycode.java:361)

Thanks.

Answer

Jurius picture Jurius · Apr 13, 2017
ApplicationPackageManager.java
private UserInfo getUserIfProfile(int userHandle) {
    List<UserInfo> userProfiles = getUserManager().getProfiles(UserHandle.myUserId());
    for (UserInfo user : userProfiles) {
        if (user.id == userHandle) {
            return user;
        }
    }
    return null;
}

and

public List<UserInfo> getProfiles(int userHandle) {
    try {
        return mService.getProfiles(userHandle, false /* enabledOnly */);
    } catch (RemoteException re) {
        Log.w(TAG, "Could not get user list", re);
        return null;
    }
}

So, if there is something wrong with AIDL request, or user's profile is disabled you will have NPE in ApplicationPackageManager.java code. I think it is impossible to prevent this situation, and I advise you to wrap notification creation in try{}catch block