Mark Harrop Mark Harrop - 1 month ago 8
Android Question

ExpandableListView array lists won't stay in the order I put them

I'm making use of the ExpandableListView and I have a few lists set in an array lists.

I set them to be in a certain order which is:

company, day of the week, posh vehicles, topgear vehicles


but what ever I do the order reverts to

posh vehicles, company, days of the week, topgear vehicles


Can anybody help me figure out the problem here is the code I'm using for the stringArray?

public static HashMap<String, List<String>> getData() {

HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();

List<String> listDataHeader = new ArrayList<String>();
// Adding child data
listDataHeader.add("Company");
listDataHeader.add("Please pick a day");
listDataHeader.add("Posh Vehicles");
listDataHeader.add("TopGear Vehicles");

List<String> CompanyName = new ArrayList<>();
CompanyName.add("Posh limos");
CompanyName.add("TopGear limos");

List<String> daysOftheWeek = new ArrayList<>();
daysOftheWeek.add("Monday");
daysOftheWeek.add("Tuesday");
daysOftheWeek.add("Wednesday");
daysOftheWeek.add("Thursday");
daysOftheWeek.add("Thursday");
daysOftheWeek.add("Friday");
daysOftheWeek.add("Saturday");
daysOftheWeek.add("Sunday");

List<String> poshvehicles = new ArrayList<>();
poshvehicles.add("Posh H2 limo");
poshvehicles.add("Iveco party bus");
poshvehicles.add("Merc party bus ");
poshvehicles.add("Party coach");

List<String> topGearVehicles = new ArrayList<>();
topGearVehicles.add("TopGear H2 limo");
topGearVehicles.add("TopGear party bus");

expandableListDetail.put(listDataHeader.get(0),CompanyName);
expandableListDetail.put(listDataHeader.get(1),daysOftheWeek);
expandableListDetail.put(listDataHeader.get(2),poshvehicles);
expandableListDetail.put(listDataHeader.get(3),topGearVehicles);

return expandableListDetail;

Answer

The HashMap doesn't keep the insertion order.

You can use a LinkedHashMap instead (which extends HashMap):

Map<String, List<String>> expandableListDetail = new LinkedHashMap<>();

I also used the interface name on the left side Map and the diamond operator (<>) that works if you have at least Java 7.