androidruntime-permissionsunboxing

Unboxing of 'perms.get(Manifest.permission.ACCESS_FINE_LOCATION)' may produce 'NullPointerException'


I am seeing this warning after updating my project to the latest 30 (buildToolsVersion "30.0.2"). How to resolve this warning?

onRequestPermissionsResult code as follows ::

switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {

                Map<String, Integer> perms = new HashMap<>();

                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);

                // Fill with actual results from user
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);

                    if ((perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                    ) {
                        // do some task
                    } else {

                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                            showDialogOK(getResources().getString(R.string.some_req_permissions));
                        } else {
                            explain(getResources().getString(R.string.open_settings));
                        }
                    }
                }
            }
            break;

            default:
                break;
        }

Solution

  • Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing, as per the official docs of Autoboxing and Unboxing. When you try to unbox a value that can possibly be null, this warning of a possible NullPointerException shows up.

    To get rid of this warning, using getInt() instead of get() should help. You can also add a null check on the value too.

    Based on the provided code in the edits, use ActivityCompat.checkSelfPermission() instead of trying to fetch a possible null value of Manifest.permission.ACCESS_FINE_LOCATION from params HashMap. Use the following code snippet if required:

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
      // do some task
    } else {
      ...
    }