0

I have tried following a tutorial series Storage permission error in Marshmallow and implemented this code

Code: Main Activity

public class MainActivity extends AppCompatActivity {

    ToggleButton toggleButton;
    TextView textView;
    Context context = getApplicationContext();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleButton = findViewById(R.id.toggleButton);
        textView = findViewById(R.id.textView);
        context.startActivity(new Intent(context, CheckPermissionsActivity.class));
    }

    public void onClickWifiBtn(View view) throws NullPointerException {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if(wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
            textView.setText("Turn ON");
            Toast.makeText(getApplicationContext(),"Wifi is Off", Toast.LENGTH_SHORT);
        }else {
            wifiManager.setWifiEnabled(true);
            textView.setText("Turn Off");
            Toast.makeText(getApplicationContext(),"Wifi is On", Toast.LENGTH_SHORT);
        }
    }
}

I have maintained a flag onRequestPermissionsResult in order to maintain permission status in

Code: CheckPermissionActivity

public class CheckPermissionsActivity extends AppCompatActivity {

    private String[] permissions;
    private int pCode = 12321;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkPermissions();
    }
    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            permissions = new String[]{Manifest.permission.INTERNET,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.CHANGE_NETWORK_STATE};

            boolean flag = false;
            for (String s : permissions) {
                if (checkSelfPermission(s) != PackageManager.PERMISSION_GRANTED) {
                    flag = true;
                    Log.d("perm tag", s);
                }
            }
            if (flag) {
                Log.d("perm tag", " In here");
                requestPermissions(permissions, pCode);
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == pCode) {
            boolean flag = true;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)
                for (int i = 0, len = permissions.length; i < len; i++)
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
                        flag = false;
        }
    }
}

Code: Manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

Error Log:

2020-05-22 14:28:13.203 25767-25767/? E/xample.p2pmyap: Unknown bits set in runtime_flags: 0x8000
2020-05-22 14:28:13.301 25767-25795/com.example.p2pmyapp E/Perf: Fail to get file list com.example.p2pmyapp
2020-05-22 14:28:13.301 25767-25795/com.example.p2pmyapp E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-05-22 14:28:13.301 25767-25795/com.example.p2pmyapp E/Perf: Fail to get file list com.example.p2pmyapp
2020-05-22 14:28:13.301 25767-25795/com.example.p2pmyapp E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
2020-05-22 14:28:13.330 25767-25767/com.example.p2pmyapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.p2pmyapp, PID: 25767
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.p2pmyapp/com.example.p2pmyapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3195)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3410)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2017)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7397)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:118)
    at com.example.p2pmyapp.MainActivity.<init>(MainActivity.java:18)
    at java.lang.Class.newInstance(Native Method)
    at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
    at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3183)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3410) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2017) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:214) 
    at android.app.ActivityThread.main(ActivityThread.java:7397) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935) 
  • You need to call `getApplicationContext()` inside your `onCreate` Method. Check https://stackoverflow.com/a/42351459/9263083 – sanoJ May 22 '20 at 12:10
  • I tried doing as you suggested but it still gives same Error @sanoJ – Kishan Dhrangadhariya May 22 '20 at 12:20
  • It's weird. It should work when `Context context = getApplicationContext();` is moved below `super.onCreate(savedInstanceState);`. Also you don't need runtime permission for the permissions you need. It's granted automatically when the user install the app. Check https://stackoverflow.com/a/36937109/9263083 – sanoJ May 22 '20 at 12:42
  • I understand that I don't need to get permission on runtime for above mentioned permission, but i might need location in future, and for that we are required to get permission on runtime I am new on android development on don't understand concepts that are bit different than that of Java – Kishan Dhrangadhariya May 22 '20 at 12:47

1 Answers1

0

Can you try the following code.I have commented the changes i did. For more information on context, activity etc check this

public class MainActivity extends AppCompatActivity {

    ToggleButton toggleButton;

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleButton = findViewById(R.id.toggleButton);
        textView = findViewById(R.id.textView);
        // Instead of ApplicationContext Use Activity Context when you want to start another activity
        startActivity(new Intent(MainActivity.this, CheckPermissionsActivity.class));
    }

    public void onClickWifiBtn(View view) throws NullPointerException {
        // Here use the ApplicationContext
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
            textView.setText("Turn ON");
            // Instead of ApplicationContext Use Activity Context for UI related things
            Toast.makeText(MainActivity.this, "Wifi is Off", Toast.LENGTH_SHORT);
        } else {
            wifiManager.setWifiEnabled(true);
            textView.setText("Turn Off");
            // Instead of ApplicationContext Use Activity Context for UI related things
            Toast.makeText(MainActivity.this, "Wifi is On", Toast.LENGTH_SHORT);
        }
    }
}
sanoJ
  • 2,935
  • 2
  • 8
  • 18
  • I tried this code It works for the Error. Logcat no longer shows any error. But for some reason it generates some issue with UI. my app no longer shows any "View" https://ibb.co/jyCNktn, this cotains xml code and xml layout https://ibb.co/SvD2yHK, this link contains screenshot of the app – Kishan Dhrangadhariya May 22 '20 at 15:08
  • Blank screen i got was UI generated because of CheckPermissionActivity after navigating backward I got the UI according to xml layout But I still can not change wifi state using toggle button – Kishan Dhrangadhariya May 22 '20 at 15:27
  • You haven't linked the onClick listener of the toggle Button. Check this https://stackoverflow.com/a/19647589/9263083 – sanoJ May 22 '20 at 16:09