Search code examples
androidnullpointerexceptionnetwork-connection

how to check internet connection in Google nexus 7 (android 4.2)


I used following code for checking internet connection.

 public static boolean checkNetworkConnection(Context context) {
        boolean connected = true;
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState() == android.net.NetworkInfo.State.CONNECTED
                || connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_WIFI).getState() == android.net.NetworkInfo.State.CONNECTED) {
            connected = true;
        } else
            connected = false;
}

This code is working fine in below mobile. But it is not working in Google nexus 7 (android 4.2).

When I test this code in Google nexus 7 (android 4.2). I got error.

Null pointer exception in connection manager


Solution

  • For me it work:

    public static boolean isInternetEnabled() {
        ConnectivityManager conMgr = (ConnectivityManager) YourApp.context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting())
            return true;
        else
            return false;
    }