-5

I am trying to fetch currency values from Yahoo! Finance using Yahoo! API into my android app.

But for some currencies, there is no value found which results in crashing my app.

If any value is not found, it should show the error.

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;
Daniel Puiu
  • 933
  • 6
  • 21
  • 27
Rahul Shaw
  • 29
  • 1
  • 9

1 Answers1

-1

Probably, because of using getString() method, just use while parsing optString() method instead of 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, "");
    }
huseyin
  • 1,137
  • 13
  • 18