Issue
Dears.
I am able to retrieve a JSON object from Alpha Vantage to use in my currency converter application but I am unable to look up for the string value I want (i.e "5. Exchange Rate": "17.86300000") because the identifier has spaces as below:
{ "Realtime Currency Exchange Rate": { "1. From_Currency Code": "USD", "2. From_Currency Name": "United States Dollar", "3. To_Currency Code": "EGP", "4. To_Currency Name": "Egyptian Pound", "5. Exchange Rate": "17.86300000", "6. Last Refreshed": "2017-12-24 14:38:20", "7. Time Zone": "UTC" } }
and hereunder my code to capture the string value
@Override
protected String doInBackground(String... f_url) {
String urlStr = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency="
+ textto.getText()
+ "&to_currency="
+ textfrom.getText()
+ "&apikey=XXXXXXXXX";
String data="";
String converted="";
try {
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line ="";
while (line != null)
{
line=bufferedReader.readLine();
data = data +line;
}
JSONArray JA = new JSONArray(data);
JSONObject JO = (JSONObject) JA.get(0);
converted = JO.getString("5. Exchange Rate");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return converted;
}
The method return blank value with no exceptions in logcat. I have tested the code with another JSON object with no spaces in identifier and works well.
Any help what I am missing here?
Solution
There is no array in you response json instead try this :
JSONObject reader = new JSONObject(data);
JSONObject sys = reader.getJSONObject("Realtime Currency Exchange Rate");
String currency = sys.getString("5. Exchange Rate");
Answered By - Abubakker Moallim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.