NullPointerException when checking Network-State on Samsung devices

422 Views Asked by At

I have released my app in Play Store and I am using the following method for checking the network state:

public class TestInternetConnection {

    public boolean checkInternetConnection(Context context) {

         ConnectivityManager con_manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

         if (con_manager.getActiveNetworkInfo() != null && con_manager.getActiveNetworkInfo().isAvailable() && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}

In the Google Play Console I see that Samsung devices crash when calling the checkInternetConnection method with a Nullpointerexception. What is the problem? On my devices and others it works just fine.

StackTrace:

java.lang.NullPointerException: 
      at de.name.app.TestInternetConnection.checkInternetConnection (TestInternetConnection.java)
      at de.name.app.SubstitutionInfoFragment$2.run (SubstitutionInfoFragment.java)
      at java.lang.Thread.run (Thread.java:762)
2

There are 2 best solutions below

1
Reaz Murshed On BEST ANSWER

You need to modify your function like this works fine for me in all device. Just to add the null check on context before you proceed.

public static boolean checkInternetConnection(Context context) {
    // Add a null check before you proceed
    if (context == null) return false;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null && info.isConnected();
}
0
Leo Aso On

Reaz Murshed's answer should fix your immediate problem, but before doing that, I think you should go through your stack trace and find out exactly where your app is passing a null context to checkInternetConnection. That's where the real source of the bug is.