I am trying to add an object to an arraylist but when I view the results of the array list, it keeps adding the same object over and over to the arraylist. I was wondering what the correct way to implement this would be.
public static ArrayList<Person> parsePeople(String responseData) {
ArrayList<Person> People = new ArrayList<Person>();
try {
JSONArray jsonPeople = new JSONArray(responseData);
if (!jsonPeople.isNull(0)) {
for (int i = 0; i < jsonPeople.length(); i++) {
People.add(new Person(jsonPeople.getJSONObject(i)));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
}
return People;
}
I have double checked my JSONArray data and made sure they are not duplicates. It seems to keep adding the first object over and over.
There is either a problem with the responseData string or the constructor.
If the class receives a response Data object that looks like the following
Then your Contact class should look like
There should be no reason based on your logic to have the same record show up twice. Make sure your JSON string has the correct format coming in. I would suggest adding more System.out or Log4j calls in the application to determine every step. Worst case step through the application with a debug session.
PS – I built you app by adding the above code and it worked fine. So you have the grasp on adding the elements to the ArrayList properly. Could you also show how you print the array back out? Maybe the issue is there.