Naseem Naseem - 2 months ago 17
Android Question

Adding an object to a arraylist inside a nested for loop

I'm trying to loop a JSON array to an array list Category and a nested Arraylist SubCategory.

My problem is that my list not only gets populated with the first SubCategory data, but also the second SubCategory data.

For example, I want:

1st category [Apple, Kiwi]
2nd category [Mango, Banana]


But instead I get,

2nd category populate as
[Apple,Kiwi,Mango,Banana]
.

ArrayList<Category> categoryName=new ArrayList<Category>();
ArrayList<ArrayList<SubCategory>> subCategoryName = new ArrayList<ArrayList<SubCategory>>();
ArrayList<Integer> subCategoryCount = new ArrayList<Integer>();

ArrayList<SubCategory> subCategoryMatches = new ArrayList<SubCategory>();
try {
// Parsing json array response
// loop through each json object

for (int i = 0; i < response.length(); i++) {

JSONObject allCategory = (JSONObject) response
.get(i);

int id = allCategory.getInt("mcatid");
String description = allCategory.getString("description");

Category categoryDetails = new Category();
categoryDetails.setCatCode(id);
categoryDetails.setCatName(description);
category_name.add(categoryDetails);

//Log.i(TAG, String.valueOf(description));

JSONArray allSubCategory = allCategory
.getJSONArray("Subcatergory");

for (int j = 0; j < allSubCategory.length(); j++) {

JSONObject jsonObject = allSubCategory.getJSONObject(j);

String subCatId = jsonObject.getString("id");

String subDescription = jsonObject.getString("description");

// retrieve the values like this so on..

//Log.i(TAG, String.valueOf(subDescription));


SubCategory subCategoryMatch = new SubCategory();
subCategoryMatch.setSubCatName(subDescription);
subCategoryMatch.setSubCatCode(subCatId);
subCategoryMatches.add(subCategoryMatch);

}

subcategory_name.add(subCategoryMatches);
subCatCount.add(subCategoryMatches.size());
}

Answer Source

You're adding to the same subCategoryMatches list reference, and so you'll get all data within one object.

You need a new list prior to the loop that adds to it.

ArrayList<SubCategory> subCategoryMatches;

try {
    // Parsing json array response
    // loop through each json object

    for (int i = 0; i < response.length(); i++) {
        ...

        // New list
        subCategoryMatches = new ArrayList<SubCategory>();

        // Loop and add
        for (int j = 0; j < allSubCategory.length(); j++) {
            ...
            subCategoryMatches.add(subCategoryMatch);
        }

        // Add new list to outer list
        subcategory_name.add(subCategoryMatches);
    }
}