[updated code] (Sorry guys, I didn't provide the whole code, because in my experience large codes seem to "scare off" possible helpers.)
For an ExpandableListView I want to build a HashMap<String, ArrayList<String>> where String is the name of a category and ArrayList<String> the names of animals belonging to that category. I populate the HashMap as such:
HashMap<String, ArrayList<String>> map_groups_childs;
ArrayList<String> list_group_titles;
private void prepareListData(ArrayList<Id_triv_cat> search_results) {
list_group_titles = new ArrayList<String>(); // this is a list of group titles
map_groups_childs = new HashMap<String, ArrayList<String>>(); // this is a map. each group title gets a list of its respective childs
// temporary List of items for a certain category/group
ArrayList<String> temp_childs_list = new ArrayList<String>();
// "search_results" is an ArrayList of self defined objects each containing an ID, a name and a category name
int count = search_results.size();
int i_cat = 0;
int i=0;
// if category "i" is the same as the next category "i+1", add child to list
for (i=0; i<count-1; i++) {
// build group with category name
list_group_titles.add(search_results.get(i).get_type());
// while category does not change, add child to the temporary childs-array
while (i<=count && search_results.get(i).get_type().equals(search_results.get(i+1).get_type())) {
temp_childs_list.add(search_results.get(i).get_name());
i++;
}
// must be done, as the while loop does not get to the last "i" of every category
temp_childs_list.add(search_results.get(i).get_name());
Log.i("DEBUG", temp_childs_list.size()); // --> returns always more than 0
Log.i("DEBUG", temp_childs_list.toString()); // --> returns always something like [word1, word2, word3, ...]
Log.i("DEBUG", list_group_titles.get(i_cat)); // --> returns always a single word like "Insekten"
// add [group_title:list_of_childs] to map
map_groups_childs.put(list_group_titles.get(i_cat++), temp_childs_list);
// clear temp_list, otherwise former category's species will be added to new category
temp_childs_list.clear();
}
Log.i("DEBUG", map_groups_childs.containsKey("Insekten")); // --> returns true
Log.i("DEBUG", map_groups_childs.size()); // --> returns 10
Log.i("DEBUG", map_groups_childs.get("Insekten").size()); // --> returns 0
Log.i("DEBUG", map_groups_childs.toString()); // --> returns {Insekten=[], Reptilien=[], ...}
}
The use of the same i in the for- and while-loop may seem wrong or confusing, but it is okay. No i is skipped in any way or used twice.
All keys I put in the HashMap are there, but the ArrayList I want to get with (for example) map_groups_childs.get("Insekten") is empty. What am I doing wrong?