0

I'm trying to request permissions on Android but I have an error.

Unable to start activity ComponentInfo {[...]}:java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference    
[...]  
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference  
at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:91)  
at android.app.Activity.requestPermissions(Activity.java:4284)  
at android.support.v4.app.ActivityCompat.requestPermissions(ActivityCompat.java:507)  
at com.appwifi.Wifi.Wifi.setPermission(Wifi.java:118)  
at com.appwifi.Wifi.Wifi.connect(Wifi.java:62)  
at com.appwifi.Wifi.Wifi.<init>(Wifi.java:51)  
at com.appwifi.Main.MainActivity.onCreate(MainActivity.java:32)  

I think i have understood it's a NullPointerException but even with debugger i can't find what is null.
Here is the code :

public class Wifi extends Activity {
    public static final int WIFI_PERMISSION = 1;
    [...]
    private void setPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED)) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE,Manifest.permission.CHANGE_WIFI_STATE,Manifest.permission.ACCESS_COARSE_LOCATION},WIFI_PERMISSION); // Error is on this line
    }
}

'this' can't be null, a new String and a static number too

I know there is some similar topic but each are very specific and i didn't find any solution. Can't understand please help me.

Rellic
  • 13
  • 3
  • Add more code details this can be context issue here. – santosh kumar May 11 '18 at 15:00
  • Your **`mContext`** is **`null`** – AskNilesh May 11 '18 at 15:23
  • It's not that `this` is null. It's that the private `Context` field in an ancestor class of `Activity` is null. Your `Wifi` class should not extend `Activity`, as it seems that you're directly instantiating it yourself in `MainActivity`'s `onCreate()`. – Mike M. May 11 '18 at 23:07

0 Answers0