【问题标题】:Android app crashes when value is not found找不到值时 Android 应用程序崩溃
【发布时间】:2016-06-06 12:20:56
【问题描述】:

我正在尝试从 Yahoo! 获取货币值使用 Yahoo! 进行财务API 到我的 android 应用程序中。

但对于某些货币,没有找到导致我的应用程序崩溃的值。

如果没有找到任何值,它应该显示错误。

String s;
String exResult = "";
final String val[];
val  = getResources().getStringArray(R.array.value);
try {
    s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
    JSONObject jObj;
    jObj = new JSONObject(s);
    exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");

    System.out.println(exResult);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return exResult;

【问题讨论】:

标签: android exception-handling crash


【解决方案1】:

可能是因为使用了 getString() 方法, 只是在解析时使用 optString() 方法而不是 getString()

.getString("率"); --> .optString("率");

 /**
     * Returns the value mapped by {@code name} if it exists, coercing it if
     * necessary, or throws if no such mapping exists.
     *
     * @throws JSONException if no such mapping exists.
     */
    public String getString(String name) throws JSONException {
        Object object = get(name);
        String result = JSON.toString(object);
        if (result == null) {
            throw JSON.typeMismatch(name, object, "String");
        }
        return result;
    }

    /**
     * Returns the value mapped by {@code name} if it exists, coercing it if
     * necessary, or the empty string if no such mapping exists.
     */
    public String optString(String name) {
        return optString(name, "");
    }

【讨论】:

    猜你喜欢
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    相关资源
    最近更新 更多