在运行时检查权限时,活动上下文空指针错误

时间:2016-11-13 05:51:16

标签: android nullpointerexception android-permissions android-context

我正在尝试确保在第一次运行闹钟应用程序时,允许为新设备读取外部存储。

我不断收到上下文的空指针错误。它在这一行:

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

我收到了这个错误:

 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

我试过(Activity)context,getParent(),this.context,getApplicationContext,正如你在下面看到的只是上下文。所有这些都有相同的结果。

提前感谢您的帮助。

这是整个代码:

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;
    }
}

1 个答案:

答案 0 :(得分:5)

您的变量contextnull且毫无用处。如果您需要在内部类(例如this' s中引用它,请使用AppCompatActivity(引用当前MainActivity.this)或AlertDialog onClick方法)。