2

I have an android app that tried to connect to a website in an AsyncTask and perform some tasks. My application always seems to crash when there is a change in the network connection i.e The app is connected to a wifi network initially, but loses connection and switches to mobile network. When this happens my Android Application crashes. My code is surrounded within a try catch block, so I'm not sure why the application would crash ? How do I fix my problem ?

Thanks!

RagHaven
  • 4,156
  • 21
  • 72
  • 113
  • 5
    plz post your task and logcat.. – Nermeen Dec 05 '12 at 08:29
  • I cannot comment on the try/catch failure, but the initial crash cause is probably insufficient error checking when a connection gets unexpectedly terminated due to the switch. – Ken Y-N Dec 05 '12 at 08:30
  • 1
    Surrounding something with a try-catch block has nothing to do with whether your application crashes or not. For example, you try to access a resource. It fails and throws an exception. You catch it, but don't do anything with it. Later, you try to use the resource which is null because the access failed and boom, null pointer exception. As Nunu said, logcat and code or no-one can help. – Simon Dec 05 '12 at 08:33

2 Answers2

0
WifiInfo info = WifiManager.getConnectionInfo();
if (info.getSSID() != null) {
    String ssid = info.getSSID();
    ...
}

I don't know if it would be overkill to write:

if (info != null && info.getSSID() != null)

Also, the BroadcastReceiver that I need to monitor when a connection is made is WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION. It turns out that I had a copy and paste error in my onResume(), and I wasn't really registering WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION.

or u can use following link

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

Community
  • 1
  • 1
NikhilReddy
  • 6,904
  • 11
  • 38
  • 58
0

You have to make sure you wait for a network connectivity to be available before continuing your websites connections.

Plus, be aware that if you try to enable a mobile connection without disabling WiFi beforehand, the Android system will automatically shutdown the newly enabled mobile connection (it gives priority to WiFi to sum up). So you need to make sure you do it in the right order :

  1. (WiFi enabled)
  2. (WiFi ready)
  3. Websites connections STARTED
  4. Websites connections STOPPPED
  5. (WiFi disabled)
  6. (WiFi unavailable)
  7. (Mobile enabled)
  8. (Mobile ready)
  9. Websites connections RESUMED
PeterGriffin
  • 910
  • 8
  • 19