0

I'm getting an error in ConnectivityManager when loading the app. I've used it a lot but this is the first time I've encounter it.

it says null but I don't have an idea what this error cause.

this is my code:

   final ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (wifi.isConnected()) {
                baseUrl = URL1;
            } else if (mobile.isConnected()) {
                baseUrl = URL2;
            }

and this is the error on Logcat

enter image description here

enter image description here

FroyoDevourer
  • 129
  • 11

2 Answers2

0

getContext() may become null when your activity is killed or app goes to background. Since this may happen in runtime, use try-catch.

try {
    final ConnectivityManager connMgr = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    ...
} catch (Exception e) {
    ...
}
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
0
Please Use this code--
and make sure that you context should not be null.

    enter code here
public static boolean checkConnectivity(Context context){
        boolean isConnected = false;
        try{
            ConnectivityManager connService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo network = connService.getActiveNetworkInfo();
            if(network != null) {
                State state = network.getState();

                if(network.isConnected()){
                    isConnected = true;
                }
            }else{
                isConnected = false;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return isConnected;
    }