samedi 21 mars 2015

Parsing JSON to custom ArrayList, only returning last item?

I'm finding this a bit odd, I'm parsing some JSON from a file in my /assets folder. I have set up a custom ArrayList, you can see it below. Now when I try and add data from the ArrayList to a listview, or a spinner (Same adapter) it only shows the last item. Here is my code:


My parsing method:



public ArrayList<Data> parseJSON(String json) {

ArrayList<Data> data = new ArrayList<>();
Data item = new Data();

Log.d(TAG, json);
try {

JSONArray jArray = new JSONArray(json);

for (int i=0; i < jArray.length();i++) {
JSONObject jObject = jArray.getJSONObject(i);
item.setFromCurrency(jObject.getString("from"));
item.setToCurrency(jObject.getString("to:"));
item.setRate(jObject.getString("rate"));
data.add(item);
}
} catch (JSONException je) {
Log.d(TAG, je.getMessage());
}
return data;
}


Here is the JSON:



[{
"from": "GBP",
"to:": "USD",
"rate": "1.5"
},
{
"from": "GBP",
"to:": "EUR",
"rate": "1.2"
},
{
"from": "GBP",
"to:": "EUR",
"rate": "1.2"
}]


In my BaseAdapter I'm doing doing this to show it in a listview: Context context; ArrayList objects;



public Array(Context context, ArrayList<Data> objects) {
super();
this.context = context;
this.objects = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

if (convertView == null) {
convertView = inflater.inflate(R.layout.spinner_row, parent ,false);
}

TextView test = (TextView) convertView.findViewById(R.id.from_data);
test.setText(objects.get(position).getRate());

return convertView;
}


Here is the custom part to my ArrayList:



private String from_currency, to_currency, rate;

public String getFromCurrency() {
return from_currency;
}

public void setFromCurrency(String from_currency) {
this.from_currency = from_currency;
}

public String getToCurrency() {
return to_currency;
}

public void setToCurrency(String to_currency) {
this.to_currency = to_currency;
}

public String getRate() {
return rate;
}

public void setRate(String rate) {
this.rate = rate;
}


My ListView XML as requested:



<ListView
android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>


I'm not quite sure where my error is. Am I parsing it incorrectly, maybe, storing it incorrectly? I have a feeling it's my ArrayList but I'm sure what I should be doing to fix it, I've tried using different Adapters, and searching StackOverflow but they all have difference issues so it's hard to narrow now.


I would appreciate your help on this. Thank you.


Aucun commentaire:

Enregistrer un commentaire