Hello Android programmers,
I am working on parsing a website in my application.
This is the website: https://raw.github.com/currencybot/open-exchange-rates/master/latest.json
The problem with this code segment is that it is not getting the rates in order.
private class DownloadWebPageTask extends AsyncTask<String, Void, ArrayList<Double>>
{
protected ArrayList<Double> doInBackground(String... urls)
{
ArrayList<Double> response = new ArrayList<Double>();
for (String url : urls)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(content);
StringBuilder sb = new StringBuilder();
char[] buffer = new char[1024];
while (isr.read(buffer) != -1)
{
sb.append(buffer);
}
JSONObject jobj = new JSONObject(sb.toString());
JSONObject ratesObj = jobj.getJSONObject("rates");
Iterator<String> keys = ratesObj.keys();
while (keys.hasNext())
{
response.add(Double.parseDouble(ratesObj.getString(keys.next())));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(ArrayList<Double> result)
{
currency_values = result;
}
To test this class, I used the following line of code:
test.setText(currency_values.get(0).toString()); //test is a TextView
The answer should be 3.6733 (if you look at the website), because it is the first rate in the ArrayList. However, it returns 82.894997, which is later found under JPY.
Why would this be happening? Does anyone have a fix for this?
That would be because JSONObject is probably using a simple Map (not a sorted one) to store the field/value combinations. The solution is to update your JSON, actually. The problem is that you want an array of rates. Like this:
Actually, I lied, a rate should look like this:
Edit:
To sort the results, store them first into an object with a String field and a Double field, then you can sort them by name and display them in order.