Reputation: 7266
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.
Upvotes: 0
Views: 1690
Reputation: 33505
So at first, you should check your response. This is best approach
if (urlConntection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// method body
}
else {
/// get some info for example with Toast or Dialog
}
You should decide to use runOnUiThread
when you want to update UI
from Non-UI thead
YourActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
Or use Handler
or AsyncTask
When you decide to use AsyncTask
, you can simply show almost everything
protected void onProgressUpdate(String... data) {
if(data[0].equals("error")) {
Toast.makeText(Activity.this, "Connection is busy!", Toast.LENGTH_SHORT).show();
}
also simply show Dialog
. It's up to you.
Upvotes: 2