简体   繁体   中英

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM