Amanda_Panda
Amanda_Panda

Reputation: 1186

Stopping WP7 app from crashing when there is no network connection

I'm working on a simple WP7 app that displays BART arrivals from their real time XML feed. I have that part working, but I need to solve this problem so it will be certified for the Marketplace.

When I debug the app on my WP7 device in airplane mode, when I try fetching the XML info, the app crashes.

The method I found online to test for network connectivity seems to do the trick:

private bool InternetIsAvailable()
    {
        var available = !NetworkInterface.GetIsNetworkAvailable();
        #if DEBUG
        available = false;
        #endif
        if (!available)
        {
            MessageBox.Show("No internet connection is available.  Try again later.");
            return false;
        }
        return true;
    }

The code is called like this (in the same code that calls the method that fetches the XML, but right before it):

bool foo;
foo=InternetIsAvailable();
if (foo == false)
       {
           NavigationService.Navigate(new Uri("/map.xaml", UriKind.Relative));


       }

My thinking here, is that if there is no network access, the app will go back to the previous page, until such time as there is network access (rather than crash-and map.xaml is the previous page). However, the app still crashes after it detects there is no network access. What am I doing wrong here? I'm also sorta learning C# at the same time, so is there some exception handling thing I'm missing?

Thanks

Upvotes: 0

Views: 685

Answers (1)

Bil Simser
Bil Simser

Reputation: 1723

Without seeing the rest of your code I can't tell why it's crashing so there could be a lot of reasons that have nothing to do with network access.

The call to GetIsNetworkAvailable is correct but the code around it is a little confusing (using a negative value then comparing that then returning the value). A lot of negative comparisons just make the code a little less readable.

How are you testing the system if there's no network available? On the emulator you can't do this. On a real device you have to put the phone into airplane mode. Just turning off the network isn't enough.

Also I would consider having this method do nothing but return the state of the network and let something else (the caller) handle the notification. This way you can reuse it anywhere you need to check without tying yourself to a UI.

The last thing is not to use Navigate if you want to redirect the user. This is still going to keep the backstack growing. If there's no network available, it's probably better to use NavigationService.GoBack() which effectively returns the user to the previous page (as is they hit the back button).

Upvotes: 1

Related Questions