简体   繁体   中英

NullPointerException when checking for permissions

I was trying to obtain runtime permissions for Android. I tried to create a class called RequestPermissions which extends MainActivity . However I get this error when asking for permissions since I wanted to separate the permission request code from MainActvity :

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference

Below are the classes

MainActivity.java

public class MainActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

  }
}

RequestPermission.java

public class RequestPermissions extends MainActivity {

 private static final int SMS_PERMISSION_REQUEST_CODE = 1;

 public RequestPermissions() {
    checkAndRequestForPermissions()
  }

  void checkAndRequestForPermissions() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
          ActivityCompat.requestPermissions(this, Manifest.permission.READ_SMS, SMS_PERMISSION_REQUEST_CODE);
        }
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == SMS_PERMISSION_REQUEST_CODE) {
// Do something here
    }
  }
}

You're requesting permissions too early. In the code:

public RequestPermissions() {
    checkAndRequestForPermissions();
}

You're checking for permissions as the RequestPermissions class is being constructed, which is before the Activity Lifecycle has begun. Therefore the Context does not yet exist.

You'll need to move checkAndRequestForPermissions() into a lifecycle method, for example onResume() as the user may have manually revoked permissions while your app was minimised. For example:

@Override
public void onResume() {
    super.onResume();
    checkAndRequestForPermissions();
}

change

ActivityCompat.requestPermissions(this, Manifest.permission.READ_SMS, SMS_PERMISSION_REQUEST_CODE);

to

ActivityCompat.requestPermissions(MainActivity.this, Manifest.permission.READ_SMS, SMS_PERMISSION_REQUEST_CODE);

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