Android - 要求GPS权限Context.getTheme()' null对象引用

时间:2018-03-06 21:11:43

标签: android android-context user-permissions android-gps

我在我的应用中使用了位置,首次安装该应用时,要求用户允许其设备上的位置。

如果他们按OK(启用位置),一切正常。但如果他们拒绝,应用程序会因此错误而崩溃:

  

尝试调用虚方法' android.content.res.Resources $ Theme android.content.Context.getTheme()'在空对象引用上

以下是与此错误相关的代码的一部分:

     if (permissionsRejected.size() > 0) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
                            showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermissions(permissionsRejected.toArray(
                                                        new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
                                            }
                                        }
                                    });
                            return;
                        }
                    }
                }

还有:

            private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

错误指向showMessageOKCancel。

我认为上下文可能存在一些问题,我在这里有:新的AlertDialog.Builder(上下文)

所以我试着添加:

private final Context mContext; 

在私人空白showMessageOKCancel内,我放 this.mContext = context;,最后放new AlertDialog.Builder(mContext)

但我仍有同样的错误

2 个答案:

答案 0 :(得分:1)

如果您使用扩展AppCompatActivity然后只传递此关键字它也工作并使用Fragment然后在警告对话框中传递getActivity()我测试mainactiviy中的代码扩展Appcompatactivity并且它没有得到任何错误。

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(this) // if fragment pass getActivity()
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

答案 1 :(得分:1)

最后,这对我的情况有帮助:

 new AlertDialog.Builder(getActivity(), R.style.Theme_AppCompat_Dialog_Alert)

工作正常!