androidnullpointerexceptionnetwork-state

NullPointerException when checking Network-State on Samsung devices


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)

Solution

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