JSONArray rewrites its contents

I am trying to generate an Array using the following method:

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();
        }
    }

The output I am getting from this code is as follows (the last line being important):

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"}]

However, I actually want this result:

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

I'm puzzled as to why the Array keeps getting overwritten with the "old" ean variables?

Answer â„–1

According to @SatelliteSD's explanation, the issue arises from using the same JSONObject within each iteration. This causes the values in that object to be updated repeatedly, resulting in multiple outputs of the same value. To rectify this problem, consider rewriting your code as shown below:

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) {
            // Handle JSON exception
            e.printStackTrace();
        }
    }
}

Answer â„–2

Your information is stored within the "json" object, as well as having a reference to that same data in your json jsArray. Consequently, when you retrieve and display the contents of the array, it will only show the data from the final assignment made within the loop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue - The module ./en.json could not be located when using the vue-i18n plugin

I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales with the correct ...

Guide on including a sum (integer) property in the JSON output of my API

Currently, I am working on an API using Express.js. In one of my functions named getAll, my goal is to not only return an array of records but also include the total number of records in the response. The code snippet below showcases how I have been handli ...

Efficient ways to organize JSON objects using JavaScript

I am in need of restructuring the data retrieved from an API call, which currently looks like this: { "Label3": [ { "name": "superman", "power": 8900 }, { "name": "iron man", "power": 3000 }, { "name": "spike spiegal", "power": 200 ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

My tests are not passing because I included a compare method in the Array prototype. What steps can I take to fix this issue in either the

Embarking on the challenging Mars Rover Kata has presented a unique problem for me. My jasmine tests are failing because of my array compare method within the prototype. This method is crucial for detecting obstacles at specific grid points. For instance, ...

Arranging objects in an array based on a separate array of strings

Here is an array of objects that I need to rearrange: var items = [ { key: 'address', value: '1234 Boxwood Lane' }, { key: 'nameAndTitle', value: 'Jane Doe, Manager' }, { key: 'contactEmail', value: ...

Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this: { "id":2026 "url": "https:// ... " , "large_url":null, "source_id":609, "copyright":"CC0", "site":"unsplash" } ...

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

How can you sort an array based on a shared object property using Angular.js?

I've been grappling with this issue for a while now. My app receives data about individuals in JSON format: "people": [ { "name": "Ivan", "city": "Moscow", "country": "Russia" }, { "name": "John", ...

Eliminate duplicate items using the reduce method in JavaScript

Working with a set of Json Objects, I use a javascript map function to list each field along with an array of its possible types. For example: birthDate, [Date, String, String, String, String] isMarried, [Boolean, Boolean, Boolean, Boolean, String] name, ...

Comparison of performance between serializing an object to indexedDB and using JSON.stringify

I am curious about the efficiency differences in terms of browser/CPU/memory between using JSON.stringify for serialization versus writing an object to an object store in indexedDB. The context for this question is optimizing the process of writing an obj ...

Harnessing the Power of Google Apps Scripts: Mastering the Art of Handling Comma-Separated Spreadsheet Values Transformed

I have a spreadsheet where column 1 contains source file IDs, with each cell holding only one ID. Column 2 has destination file IDs, where cells contain multiple IDs separated by commas. I utilize a script to retrieve these values and perform various opera ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

What are the steps to keep a web application from closing on Android when the back button is pressed?

I am currently working on a HTML5 web application and packaging it with Cordova (phonegap) 1.7. My goal is to customize the behavior of the Android back button so that instead of closing the application by default, it navigates back using window.history.b ...

What is the best way to organize a flatlist for rendering?

I'm struggling with separating some flat-lists into different components. How can I arrange the rendering of the flat-list like the sample form (Picture "Sample UI")? I've tried, but it's not working correctly as it renders flat list A first ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

Transforming a single object into multiple arrays using AngularJS

Just starting out with AngularJS and I've got some data that looks like this { day1: 0, day2: 0, day3: 0, day4: 2 } Is there a way to convert this data into arrays structured like below? [     ["day1": 0],     ["day2": 0],   ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this: [ { "name": { "common": "Aruba", "official": "Aruba", "native": { "nld": { "official ...

Struggling to convert a JSON file into a TableView within a JavaScript application developed with Appcelerator

Trying to display a JSON file in a table using JavaScript and Appcelerator is proving to be quite a challenge. The output appears as an empty table when compiled to an example page. As someone relatively new to JavaScript and JSON, I'm seeking guidanc ...