0

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

MultiplePermissions

package com.example.phonedetails;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MultiplePermissions extends AppCompatActivity {

    Context mContext;
    private static final int EXTERNAL_STORAGE_PERMISSION_CONSTANT = 100;
    private static final int REQUEST_PERMISSION_SETTING = 101;
    private static String[] permissionsRequired = new String[]{Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //private TextView txtPermissions;
    //private Button btnCheckPermissions;
    SharedPreferences permissionStatus;
    private boolean sentToSettings = false;
    final private Activity activity;

    public MultiplePermissions(Activity activity) {
        this.activity = activity;
    }


    public void GetPermissions(){

        //permissionStatus = getSharedPreferences("permissionStatus",MODE_PRIVATE);

        if(ActivityCompat.checkSelfPermission((MultiplePermissions)mContext, permissionsRequired[0]) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission((MultiplePermissions)mContext, permissionsRequired[1]) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission((MultiplePermissions)mContext, permissionsRequired[2]) != PackageManager.PERMISSION_GRANTED){
            if(ActivityCompat.shouldShowRequestPermissionRationale((MultiplePermissions)mContext,permissionsRequired[0])
                    || ActivityCompat.shouldShowRequestPermissionRationale((MultiplePermissions)mContext,permissionsRequired[1])
                    || ActivityCompat.shouldShowRequestPermissionRationale((MultiplePermissions)mContext,permissionsRequired[2])){
                //Show Information about why you need the permission
                AlertDialog.Builder builder = new AlertDialog.Builder(MultiplePermissions.this);
                builder.setTitle("Need Multiple Permissions");
                builder.setMessage("This app needs Write File and Mobile Details permissions.");
                builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        ActivityCompat.requestPermissions((MultiplePermissions)mContext,permissionsRequired,EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            } else if (permissionStatus.getBoolean(permissionsRequired[0],false)) {
                //Previously Permission Request was cancelled with 'Dont Ask Again',
                // Redirect to Settings after showing Information about why you need the permission
                AlertDialog.Builder builder = new AlertDialog.Builder(MultiplePermissions.this);
                builder.setTitle("Need Multiple Permissions");
                builder.setMessage("This app needs Write File and Mobile Details permissions.");
                builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        sentToSettings = true;
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                        Toast.makeText(getBaseContext(), "Go to Permissions to Grant  Storage  and Phone", Toast.LENGTH_LONG).show();
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            }  else {
                //just request the permission
                ActivityCompat.requestPermissions((MultiplePermissions)mContext,permissionsRequired,EXTERNAL_STORAGE_PERMISSION_CONSTANT);
            }

            //txtPermissions.setText("Permissions Required");

            SharedPreferences.Editor editor = permissionStatus.edit();
            editor.putBoolean(permissionsRequired[0],true);
            editor.commit();
        } else {
            //You already have the permission, just go ahead.
            proceedAfterPermission();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == EXTERNAL_STORAGE_PERMISSION_CONSTANT){
            //check if all permissions are granted
            boolean allgranted = false;
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    allgranted = true;
                } else {
                    allgranted = false;
                    break;
                }
            }

            if(allgranted){
                proceedAfterPermission();
            } else if(ActivityCompat.shouldShowRequestPermissionRationale((MultiplePermissions)mContext,permissionsRequired[0])
                    || ActivityCompat.shouldShowRequestPermissionRationale((MultiplePermissions)mContext,permissionsRequired[1])
                    || ActivityCompat.shouldShowRequestPermissionRationale((MultiplePermissions)mContext,permissionsRequired[2])){
                //txtPermissions.setText("Permissions Required");
                AlertDialog.Builder builder = new AlertDialog.Builder(MultiplePermissions.this);
                builder.setTitle("Need Multiple Permissions");
                builder.setMessage("This app needs Write File and Mobile Details permissions.");
                builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        ActivityCompat.requestPermissions((MultiplePermissions)mContext,permissionsRequired,EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.show();
            } else {
                Toast.makeText(getBaseContext(),"Unable to get Permission",Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PERMISSION_SETTING) {
            if (ActivityCompat.checkSelfPermission((MultiplePermissions)mContext, permissionsRequired[0]) == PackageManager.PERMISSION_GRANTED) {
                //Got Permission
                proceedAfterPermission();
            }
        }
    }

    private void proceedAfterPermission() {
        //txtPermissions.setText("We've got all permissions");
        MainActivity.bool=1;
        Toast.makeText(getBaseContext(), "We got All Permissions", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (sentToSettings) {
            if (ActivityCompat.checkSelfPermission((MultiplePermissions)mContext, permissionsRequired[0]) == PackageManager.PERMISSION_GRANTED) {
                //Got Permission
                proceedAfterPermission();
            }
        }
    }
}

i am calling that code from MainActivity and FirstRun like below.

MultiplePermissions permission= new MultiplePermissions(FirstRun.this);
permission.GetPermissions();

my Logcat

01-22 11:39:50.031 29718-29718/com.example.phonedetails E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.example.phonedetails, PID: 29718
   java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
       at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:430)
       at com.example.phonedetails.MultiplePermissions.GetPermissions(MultiplePermissions.java:41)
       at com.example.phonedetails.FirstRun$1.onClick(FirstRun.java:46)
       at android.view.View.performClick(View.java:6294)
       at android.view.View$PerformClick.run(View.java:24770)
       at android.os.Handler.handleCallback(Handler.java:790)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:164)
       at android.app.ActivityThread.main(ActivityThread.java:6494)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

If Know How to fix it please tell me I am beginner.

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
Azar Kazi
  • 11
  • 5
  • what is `ActivityCompat` and where is it set? Hint: it is not not set so it is null – Scary Wombat Jan 22 '18 at 06:31
  • 1
    `MultiplePermissions` should not be an `Activity` unless it's being used as an `Activity`, which seems very unlikely from that code. – Mike M. Jan 22 '18 at 06:33
  • If this were supposed to be a utility method you would need to pass in the valid Context of a calling Activity. But some of the code in your method looks very Activity-like, so this wouldn't be a good utility method. Maybe what you really want to do is put this in a generic Activity subclass for your project and then have the various individual Activities which need this capability inherit from that. – Chris Stratton Jan 22 '18 at 08:25
  • i am newly join and i am fresher also...and the above code is done by previous developer who working on it. i just want to give the run-time Multiple permissions. – Azar Kazi Jan 22 '18 at 10:53

0 Answers0