zauber3r
zauber3r

Reputation: 95

JSONArray overwrites itself

I want to create an Array this way:

json = new JSONObject();
jsArray = new JSONArray();
for (int i = 1; i < j; i++) {
    CheckBox checkBox = (CheckBox) findViewById(i);
    if (checkBox.isChecked()) {
        try {
            String ean = (String) checkBox.getText();
            json.put("ean", ean);
            jsArray.put(json);
            Log.v("jsArray", jsArray.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I get this from the code (last line is the important one):

04-06 19:07:02.238: V/jsArray(9894): [{"ean":"8029694000"}]
04-06 19:07:02.238: V/jsArray(9894): [{"ean":"8029694200"},{"ean":"8029694200"}]
04-06 19:07:02.238: V/jsArray(9894): [{"ean":"8029694300"},{"ean":"8029694300"},{"ean":"8029694300"}]

But I want this:

[{"ean":"8029694000"},{"ean":"8029694200"},{"ean":"8029694300"}]

Why the Array is overwritten with the "old" ean-variables?

Upvotes: 0

Views: 1458

Answers (2)

Jordan Martin
Jordan Martin

Reputation: 196

You put your data inside the same object json and you also add the same reference inside you json jsArray. So when you display the content of the array it show you the content of the only reference that exist and it's the last affectation in the loop.

Upvotes: 0

QuinnG
QuinnG

Reputation: 6424

As @SatelliteSD stated; you're using the same JSONObject for each iteration. This is updating the values in THAT object each time and since the array has multiple references to the same object; it's outputting the same value multiple times.
Rewriting to something like this should resolve the issue.

jsArray = new JSONArray();
for (int i = 1; i < j; i++) {
    CheckBox checkBox = (CheckBox) findViewById(i);
    if (checkBox.isChecked()) {
        try {
            String ean = (String) checkBox.getText();
            JSONObject json = new JSONObject();
            json.put("ean", ean);
            jsArray.put(json);
            Log.v("jsArray", jsArray.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Upvotes: 1

Related Questions