Android – Checking Permissions in a Separate Class

I found some other topics that touched on this, but the solutions did not work for me.

I have a class PermissionsManager.java which contains the methods for checking permission, and I make a call to it in the MainActivity.java. I read from some people that I have to pass a Context and Activity to checkPermissions(), but I tried that although the Context allow my app to work if the permissions were already granted, the app would crash if permission had not been already granted. I had trouble passing a suitable Activity.

I could just put all the code in my MainActivity and I know it works there since I had it all working, but I’d really like to set up my code in a MVC pattern to keep Views separate from controllers.

I get the following error:

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

Could anyone shed some light on how to get this to work?

PermissionsManager

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 5/6/2017.
 */

public class PermissionsManager extends AppCompatActivity {
    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;

    public void checkPermissions() {
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
            permissionsNeeded.add("Read Contacts");
        if (!addPermission(permissionsList, Manifest.permission.SEND_SMS))
            permissionsNeeded.add("Send SMS Texts");
        if (!addPermission(permissionsList, Manifest.permission.RECEIVE_SMS))
            permissionsNeeded.add("Receive SMS Texts");
        if (!addPermission(permissionsList, Manifest.permission.READ_SMS))
            permissionsNeeded.add("Read SMS Texts");


        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {
                // Need Rationale
                String message = "This app requires the following permissions to function correctly: n" + permissionsNeeded.get(0);
                for (int i = 1; i < permissionsNeeded.size(); i++)
                    message = message + "n" + permissionsNeeded.get(i);
                showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                                }
                            }
                        });
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            }
            return;
        }
    }

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

    private boolean addPermission(List<String> permissionsList, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permission);
                // Check for Rationale Option
                if (!shouldShowRequestPermissionRationale(permission))
                    return false;
            }
        }
        return true;
    }
}

MainActivity OnCreate Method

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Check Permissions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionsManager permissionsManager = new PermissionsManager();
            permissionsManager.checkPermissions();
        }
    }

I tried some code like this, but it didn’t work for me.

if(ContextCompat.checkSelfPermission((Activity)mContext,Manifest.permission.REA
        D_SMS)!=PackageManager.PERMISSION_GRANTED)    
       {
            ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.READ_SMS},
                        MY_PERMISSIONS_REQUEST_READ_SMS);
       }

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Could anyone shed some light on how to get this to work? Step #1: Never create an instance of an activity yourself, as it simply does not work and results in exceptions like the one that you have. Get rid of PermissionsManager permissionsManager = new PermissionsManager();. Step #2: Have MainActivity extend from PermissionsManager. I’d really like to set up my code in a MVC pattern to keep Views separate from controllers I don’t see how MVC ties into here. Regardless, your activity has to be at least somewhat aware of permissions, as your activity has to implement onRequestPermissionsResults(). If you… Read more »