0

When I click a button to sort the listview, it works but only if I start scrolling the listview does it show the sort order.

This is what I have in my data model class:

    public static Comparator<Emplyoyee> sortNameAtoZ = new Comparator<Emplyoyee>() {

        @Override
        public int compare(Emplyoyee lhs, Emplyoyee rhs) {
            String emp1 = lhs.getName();
            String emp2 = rhs.getName();

            return emp1.compareTo(emp2);
            //descending order
            //return StudentName2.compareTo(StudentName1);
        }};

When the user clicks the button, I call this:

Collections.sort(rowdata, EmployeeRowData.sortNameZtoA);
adapter.notifyDataSetChanged();

After doing the research and comparing different sources, the setup is the same as it is here but it is not sorting the listview instantly upon clicking the button. I'm populating the listview with data from a remote database using Volley.

Steve C.
  • 1,333
  • 3
  • 19
  • 50

1 Answers1

2

Reset your arraylist.

try this:

Collections.sort(rowdata, EmployeeRowData.sortNameZtoA);

    adapter.setArrayList(rowdata);

    adapter.notifyDataSetChanged();

Your adaptor

public void setArrayList(ArrayList<Emplyoyee> array){
yourArray =array;
}
KDeogharkar
  • 10,939
  • 7
  • 51
  • 95
  • The first part goes in the buttons' onClick method correct? – Steve C. May 14 '16 at 06:37
  • Tried adding the first part to my buttons' onClick and it gives the error "incompatible types" . Required=ArrayList, Found=Void. I have it written exactly as you do. – Steve C. May 14 '16 at 06:45
  • if it helps, EmployeeRowData is the data model. Not sure if that makes a difference. Thats not the adapter. – Steve C. May 14 '16 at 06:47
  • Works perfectly! Thank you. I guess resetting the ArrayList using setArrayList is what was needed. – Steve C. May 14 '16 at 06:53
  • @KDeogharkar A commenter (elBradford, see here: https://stackoverflow.com/questions/9906464/sort-listview-with-array-adapter) mentioned that "The .sort function automatically calls notifyDataSetChanged, so if you use this code with the built-in sort, you'll get into an infinite loop and overflow your stack." So is your line "adapter.notifyDataSetChanged();" needed above or can it be safely removed? – AJW Oct 12 '17 at 14:05