Nicholas Muir Nicholas Muir - 25 days ago 8
Android Question

Activity context null pointer error when checking for permissions at runtime

I am trying to ensure that on the first run of an alarm clock app that the permission to read the external storage for newer devices.

I keep getting a null pointer error for the context. It is on this line:

if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)


And I am getting this error:

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


i tried (Activity) context, getParent(), this.context, getApplicationContext and as you can see below just context. All of them had the same result.

Thanks in advance for your help.

This is the whole code:

public class MainActivity extends AppCompatActivity implements FragmentAddAlarms.onTabChangedListener {

public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
boolean result = checkPermission();
if (result) {
//writeCalendarEvent();
}

}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkPermission()
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage is necessary to for alarms!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();

} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}

Answer

Your variable context is null and useless. Just use this (which refers the the current AppCompatActivity) or MainActivity.this if you need to refer to it within an inner class (such as your AlertDialog's onClick method).