Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

java - Null pointer exception when checking for permission with android.content.Context.checkPermission

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:

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

it's a separate class, controller: public class DummyData extends Activity { .... }

That is not going to work.

Never extend Activity unless it is a real activity, one that you will register in the manifest.

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.

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.

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...