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.

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

The first part goes in the buttons' onClick method correct?
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.
if it helps, EmployeeRowData is the data model. Not sure if that makes a difference. Thats not the adapter.
Works perfectly! Thank you. I guess resetting the ArrayList using setArrayList is what was needed.
@KDeogharkar A commenter (elBradford, see here: stackoverflow.com/questions/9906464/…) 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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.