My Android App does http posts to URLs like http://example.com/abc.php?email=abc@xyz.com So the Android App basically talks to PHPs on the server side and receives JSON responses and parses them to populate various views in the App. Works fine.
My question is- How should I handle events below in the Android App so that in case these events occur in the server side application, the App should not FORCE CLOSE as it does now.
Server Time out occurs and no response is received. The App force closes now. I want to handle this appropriately.
Error Codes returned as a response to the App http post to the server. The App Force closes currently since I have not handled this.
I have encountered these two scenarios where the App is not coded to handle these events. Please feel free to add any other events that might occur that might lead ANRs occur in Android App.
A little code snippet or clue will help me a lot since I have never done this before.
Thanks.
You should also make sure you're not doing lengthy tasks like HTTP requests in the UI thread.
Adding to the very good suggestions so far...
My work associate taught me to use classes from the org.apache.http package like this:
As Kaj said in the comment, one option is to catch the exception, and perhaps retry or post a failure message.
For response codes != 200, just read them an do your job inside an
if (con.getResponseCode() == 200)
blockAnother alternative option, is to use the much nicer Apache classes:
http://developer.android.com/reference/org/apache/http/package-summary.html
For a snippet, check BalusC's tutorial here in SO: Using java.net.URLConnection to fire and handle HTTP requests