user2305208
user2305208

Reputation: 41

Android AsyncTask, handle unavailable server

I am using this tutorial: http://hmkcode.com/android-parsing-json-data/ to get JSON data from server on virtual machine. It works fine, when server is turned on, but my app crashes when server is unavailable. How should I handle this situation?

After pressing button I execute:

httpAsyncTask.execute("http://localhost:3000"); //changed on purpose, it works with given IP

httpAsyncTask class:

private class HttpAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

            return GET(urls[0]);
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Worked fine", Toast.LENGTH_LONG).show();
        goToMyActivity();
    }
}

In debug my app stops at:

HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

int GET method:

public static String GET(String url){
    InputStream inputStream = null;
    String result = "";

        try {
            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            // convert inputstream to string
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
        } catch (Exception e){
            Log.e("Http:",e.toString());
        }
    return result;
}

Caught exception was null.

Upvotes: 0

Views: 907

Answers (3)

Sabbir Sadik
Sabbir Sadik

Reputation: 36

This function will return null if it gets timeout otherwise will send the response

public static String Get(String url) {

  // Create a new HttpClient
  HttpParams params = new BasicHttpParams();
  // set your timeouts here
  HttpConnectionParams.setConnectionTimeout(params, 5000);
  HttpConnectionParams.setSoTimeout(params, 10000);
  HttpClient httpclient = new DefaultHttpClient(params);      

  try {
      // Execute HTTP GET Request
      HttpResponse response = httpclient.execute(new HttpGet(url));           
      return EntityUtils.toString(response.getEntity());

  } catch (ClientProtocolException e) {
      e.printStackTrace();
  } catch (IOException e) {
      e.printStackTrace();
  }
  return null;

}

Upvotes: 0

Xyaren
Xyaren

Reputation: 953

Use the catch block to catch the timeout exception (and others):

String message = "";
try {
    //HTTP stuff here
    if (responseCode == HttpURLConnection.HTTP_OK) {
        // do your stuff here
    } else { 
        // Show some error dialog or Toast message
    }
} catch (Exception e) {
    message  = e.getLocalizedMessage();
    e.printStackTrace();
}
// Toast message

Upvotes: 0

Sufiyan Ghori
Sufiyan Ghori

Reputation: 18753

use getResponseCode(); of HttpURLConnection class to make sure that the connection is established successfully.

getResponseCode(); would return 200 if the connection is successful.

                int responseCode = -1;
                feedURL = "your URL"
                HttpURLConnection connection;
                connection = (HttpURLConnection) feedURL.openConnection();
                connection.connect();
                responseCode = connection.getResponseCode();

then use if block to check if 200 is returned by connection.getResponseCode(). the constant HttpURLConnection.HTTP_OK can be used instead of hard coding 200.

                if (responseCode == HttpURLConnection.HTTP_OK) {
                      // do your stuff here
                }
                else { 
                     // Show some error dialog or Toast message
                }

Upvotes: 1

Related Questions