开发者

Why is catching UnknownHostException when using BufferedReader to open URL stream crashing my app?

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, whi开发者_StackOverflow社区ch 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;

}


Your problem isn't the UnknownHost but rather in your finally block you're not closing open resources correctly (not what's causing the issue, but you're essentially doing it wrong) and you're not catching all possible exceptions (this is why you're code isn't working as you expect). You are much better off having a try{ __.close(); } catch(__Exception e){...} for EACH resource you're closing. This way if one of your close() calls has an exception, the other resources still get closed, otherwise you're just leaving them open and jumping straight into the catch block in finally.

The real reason for your issue, however, is that your resources aren't getting instantiated before getting an initial exception and then going into the finally block. So, they're still null. The exception you should be catching, along with an IOException is a NullPointerException.

Hopefully this helps you out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜