0

我正在编写一个连接到网站并以 JSON 形式检索搜索结果的 Android 应用程序。此功能发生在 AsyncTask 中,它被设置为与 UI 分开的流。我需要处理连接中断/不存在/太潜在的情况。我需要处理这种情况,以便向用户显示一个 AlertDialog,让他们知道连接不好。我看到帖子建议为 URLConnection 设置超时参数,但我现在没有使用 URLConnection。

现在,当我有数据连接时,该功能完美地执行,但没有连接时则不然。当我运行模拟器并禁用我的 PC 的互联网连接时,运行该函数会显示“强制关闭”消息并产生 UnknownHostException。我遇到了这个异常,但我的应用程序仍然崩溃。

我还需要处理无法找到缩略图的情况,这会产生 FileNotFoundException。

请告诉我我应该怎么做。谢谢。

@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;

}
4

1 回答 1

1

您的问题不是 UnknownHost 而是在您的 finally 块中您没有正确关闭打开的资源(不是导致问题的原因,但您基本上做错了)并且您没有捕获所有可能的异常(这就是为什么您的代码没有按预期工作)。你最好拥有一个try{ __.close(); } catch(__Exception e){...}你要关闭的每个资源。这样,如果您的一个调用出现异常,其他资源仍然会关闭,否则您只是让它们保持打开状态close()并直接跳入catch.finally

但是,您的问题的真正原因是您的资源在获得初始异常然后进入finally块之前没有被实例化。所以,他们还在null。您应该捕获的异常以及 anIOException是 a NullPointerException

希望这可以帮助你。

于 2010-12-10T19:52:16.637 回答