我正在尝试从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;
答案 0 :(得分:-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, "");
}