gpt4 book ai didi

android - 找不到值时,Android应用程序崩溃

转载 作者:行者123 更新时间:2023-12-03 17:49:32 24 4
gpt4 key购买 nike

我正在尝试从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;

最佳答案

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

.getString(“Rate”); -> .optString(“Rate”);

 /**
* 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, "");
}

关于android - 找不到值时,Android应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com