I'm writing an Android application that is connecting to a website and retrieving search results in the form of JSON. This function is happening in an AsyncTask, which is set up as a separate stream from the UI. I need to handle the case where the connection is interrupted/non-existent/too latent. I need to handle this case in order to display an AlertDialog to the user letting them know the connection is bad. I've seen posts suggest setting a timeout parameter for URLConnection, but I'm not using URLConnection right now.
Right now, The function performs flawlessly when I have a data connection, but not so when there is no connection. When I run the emulator and disable my PC's internet connection, running the function brings up a "Force Close" message and produces an UnknownHostException. I'm catching this exception, but my application still crashes.
I also need to handle a case where no thumbnail can be found, which produces a FileNotFoundException.
Please advise me on what I should do. Thanks.
@Override
protected HashMap<String, String> doInBackground(Object... params) {
InputStream imageInput = null;
FileOutputStream imageOutput = null;
try {
URL url = new URL("http://www.samplewebsite.com/" + mProductID);
BufferedReader reader =
new BufferedReader(new InputStreamReader(url.openStream()));
String jsonOutput = "";
String temp = "";
while ((temp = reader.readLine()) != null) {
jsonOutput += temp;
}
JSONObject json = new JSONObject(jsonOutput);
// ... Do some JSON parsing and save values to HashMap
String filename = mProductID + "-thumbnail.jpg";
URL thumbnailURL = new URL("http://www.samplewebsite.com/img/" + mProductID + ".jpg");
imageInput = thumbnailURL.openConnection().getInputStream();
imageOutput = mContext.openFileOutput(outputName, Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = imageInput.read(data)) != -1) {
imageOutput.write(data, 0, read);
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
try {
imageOutput.close();
imageInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return mProductInfoHashMap;
}