3

I am using the following function to check network connectivity but application crashes when wifi status is swapped

    public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connec = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connec.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnected() == true) {
        return true;
    }
    return false;
}
xydev
  • 3,409
  • 5
  • 34
  • 54
  • 1
    Could you provide the error you get? – WarrenFaith Feb 17 '11 at 12:59
  • Post the stack trace. It seems reasonable to me that NetworkInfo would throw an exception (that you aren't catching) if you weren't connected to a network. – Mike Yockey Feb 17 '11 at 13:03
  • Does your app crash if the WiFi status is changed while your app is in the middle of performing a network operation? Or does it crash if the WiFi status is changed and you *then* run your app? – dave.c Feb 17 '11 at 13:11
  • sadly it never comes in debug mode – xydev Feb 17 '11 at 13:14
  • first after loosing connectivity , back button is pressed to reach the "page in which crash occurs".. then an alert is shown(There is no network connectivity and i press OK)..then i switch on the wifi... then there is a refresh button in which using the above fn .. connectivity is checked.. then after a blank screen app crashes – xydev Feb 17 '11 at 13:47

2 Answers2

1

it took some time to shift between networks...

So Now if we disable the wifi it automatically get connected to mobile network after few seconds.. and if we enable the wifi then it get connected to wifi network again...

The thread in your application is checking the connectivity before that shift...

check the conversation here

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

Community
  • 1
  • 1
Rohit Sharma
  • 13,787
  • 8
  • 57
  • 72
1

Are you missing a NullPointerException?

I use the following method:

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        return cm.getActiveNetworkInfo().isConnectedOrConnecting();
    } catch(NullPointerException n) {
        return false;
    }
}
dwbrito
  • 5,194
  • 5
  • 32
  • 48
  • NullPointerException comes under unchecked Exception category. It should never be checked. NullPointerException indicates a bug that a programmer forgot to bind the object to its reference. and program should terminate if it comes. – Rohit Sharma Feb 20 '11 at 02:00