使用android.content.Context.checkPermission检查权限时出现空指针异常 [英] Null pointer exception when checking for permission with android.content.Context.checkPermission
问题描述
在查询Android日历中的事件之前,我需要检查权限. 为此,Android Studio警告我在查询之前需要先进行检查. 自动生成的代码是这样的:
I need to check for permissions before querying the Android calendar for events. To do it, Android studio is warning that I need to follow a check before querying. The auto generated code is this piece:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
System.out.println("NO ACCESS TO CALENDAR!! Abort mission, abort mission!!");
}
尝试运行它时,出现此错误:
When trying to run it, I get this error:
试图调用虚拟方法'int
android.content.Context.checkPermission(java.lang.String,int,int)' 在空对象引用上
Attempt to invoke virtual method 'int
android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
因此很明显,此时某些内容为null,我尝试以不同的方式获取应用程序的上下文,但这仍然是相同的错误. 我尝试过的另一件事是这段代码,该代码应该能够处理低于Android 6的目标:
So it is clear that something is null at this point, and I tried to get the context of the app with a different way, but it's still the same error. Other thing I tried was this code, which is supposed to handle the targets lower than Android 6:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
仍然出现相同的错误,有人可以帮助我吗?
Still get the same error, can anybody help me with this?
推荐答案
这是一个单独的类,控制器:公共类DummyData扩展了Activity {....}
it's a separate class, controller: public class DummyData extends Activity { .... }
那是行不通的.
绝不扩展Activity
,除非它是真实活动,否则您将在清单中进行注册.
Never extend Activity
unless it is a real activity, one that you will register in the manifest.
从不通过构造函数(例如,代码中的new DummyData()
)创建Activity
的实例.使用startActivity()
显示您在清单中注册的活动.
Never create an instance of an Activity
via a constructor (e.g., the new DummyData()
that you have somewhere in your code). Use startActivity()
to display an activity that you have registered in the manifest.
就目前而言,虽然DummyData
类从编译的角度来看可能起作用,但它在运行时将不起作用. Activity
需要由框架实例化,而DummyData
则不是这种情况.
As it stands, while your DummyData
class may work from a compilation standpoint, it will not work at runtime. An Activity
needs to be instantiated by the framework, and that is not the case with your DummyData
.
将 real Context
对象传递给checkSelfPermission()
,并将 real Activity
对象传递给requestPermissions()
.在这种情况下,真实"的意思是从框架交给您".
Pass a real Context
object to checkSelfPermission()
, and pass a real Activity
object to requestPermissions()
. In this case, "real" means "handed to you from the framework".
这篇关于使用android.content.Context.checkPermission检查权限时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!