Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConnectivityManager null pointer

getting a null pointer problem in the code shown here. usually a null pointer is a simple and easy thing to fix, however in this case I am totally lost on the cause.

the nullPointer is on the this line:

dataConnectionStatus = connManager.getActiveNetworkInfo().isConnected();

the code shown below is located in the beginning of the onCreate method. i used similar code earlier to check if the wifi connection is active. in this case i need to check if either the wifi or the 3g data connection is active.

the situation where it crashes with the null pointer is when both the wifi and the 3g mobile data are turned off. how to avoid the null in this situation?

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

 boolean dataConnectionStatus = false;

if(connManager!=null){
dataConnectionStatus = connManager.getActiveNetworkInfo().isConnected(); //<-NULL
}
like image 813
Kevik Avatar asked Sep 11 '13 07:09

Kevik


3 Answers

getActiveNetworkInfo() is returning null.

As documentation says,

Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.

Hence, plz make sure you have access to active network.

You can try following:

    public static boolean isInternetAvailable(Context cxt) {

    ConnectivityManager cm = (ConnectivityManager) cxt
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()) {

        Log.i("NetworkStatus :", "Network connection available.");
        return true;
    }

    return false;
}
like image 171
Ritesh Gune Avatar answered Oct 28 '22 06:10

Ritesh Gune


Try like this...In this casethe connManager gets intialised and is less prone to exception

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (mWifi.isAvailable() == false && mMobile.isAvailable() == false) {
        showDialog(DIALOG_NETWORK_UNAVAILABLE);
    }
like image 42
Mayank Saini Avatar answered Oct 28 '22 04:10

Mayank Saini


Check if you have any active Network available. If not just show it as a Toast or ask to activate any one.

if(connManager!=null && connManager.getActiveNetworkInfo() != null){
    dataConnectionStatus = connManager.getActiveNetworkInfo().isConnected();
}
like image 1
AnujMathur_07 Avatar answered Oct 28 '22 05:10

AnujMathur_07