Question

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
}
Was it helpful?

Solution 3

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();
}

OTHER TIPS

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;
}

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);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top