My Android game needs to get some information about players from my server. I do this with a simple HTTP GET request, which I placed inside a thread.
The code I am using is below. When my server is up and running the app works fine. When my server is not responding (either because it’s busy or down), however, the app crashes.
Instead of the app crashing I would like to display a “Network is busy” message to the user and send him back to the main activity, but not sure how to do it.
I tried to create a dialog inside the Catch section, thinking this would show if my server was down, but it’s not showing and the app crashes.
Any ideas how I can solve this?
public void run(){
String urlstring = "http://www.mydomain.com/?param=test";
try{
URL url = new URL(urlstring);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
line = reader.readLine();
}
catch(Exception e){
Dialog d2 = new Dialog(context);
d2.setContentView(R.layout.dialog2);
d2.show();
}
}
Update: I think I found the issue looking at logcat. Even with the server down my BufferedReader was returning an empty string, and I was trying to use that down the road.
So at first, you should check your response. This is best approach
You should decide to use
runOnUiThreadwhen you want to updateUIfromNon-UI theadOr use
HandlerorAsyncTaskWhen you decide to use
AsyncTask, you can simply show almost everythingalso simply show
Dialog. It’s up to you.