LBJ33 LBJ33 - 3 months ago 30
Android Question

Expandable List View not in right order

my expandable list view doesn't seem to be in right order.

Here is my dataprovider for it:

public class DataProvider {

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

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

List<String> Workout_29 = new ArrayList<String>();
Workout_29.add("Week One");
Workout_29.add("Week Two");
Workout_29.add("Week Three");
Workout_29.add("Week Four");

List<String> Workout_30 = new ArrayList<String>();
Workout_30.add("Week One");
Workout_30.add("Week Two");
Workout_30.add("Week Three");
Workout_30.add("Week Four");

List<String> Workout_31 = new ArrayList<String>();
Workout_31.add("Week One");
Workout_31.add("Week Two");
Workout_31.add("Week Three");
Workout_31.add("Week Four");

List<String> Workout_32 = new ArrayList<String>();
Workout_32.add("Week One");
Workout_32.add("Week Two");
Workout_32.add("Week Three");
Workout_32.add("Week Four");

List<String> Workout_37 = new ArrayList<String>();
Workout_37.add("Week One");
Workout_37.add("Week Two");
Workout_37.add("Week Three");
Workout_37.add("Week Four");

WorkoutDetails.put("Workout 29", Workout_29);
WorkoutDetails.put("Workout 30", Workout_30);
WorkoutDetails.put("Workout 31", Workout_31);
WorkoutDetails.put("Workout 32", Workout_32);
WorkoutDetails.put("Workout 37", Workout_37);

return WorkoutDetails;
}

}


Here is where it is created:

public class MyWorkout extends BaseActivity{

ExpandableListView expandableListView;
HashMap<String, List<String>> Workouts_details;
List<String> Workout_list;
WorkoutsAdapter mAdapter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_workout);
mToolBar = activateToolbar();
setUpNavigationDrawer();
getSupportActionBar().setTitle("My Workout");


expandableListView = (ExpandableListView) findViewById(R.id.listViewWorkouts);
Workouts_details = DataProvider.getInfo();
Workout_list = new ArrayList<>(Workouts_details.keySet());
mAdapter = new WorkoutsAdapter(this, Workouts_details, Workout_list);



expandableListView.setAdapter(mAdapter);


As you can see it should be 29,30,31,32,37.. but in reality it is 29,30,32,37,31... Any ideas why? Thanks!

Answer

This is most likely because HashMap provides no guarantees about the ordering of its keys in the returned keyset. My guess is that if you subsequently sort the list that you build here, you would get your desired ordering:

    Workout_list = new ArrayList<>(Workouts_details.keySet());
    // Now sort Workout_list...
    // As it is simply a list of strings, we can sort it according to its natural ordering (lexicographical) to get your desired result like so:
    java.util.Collections.sort(Workout_list);
Comments