Reyjohn
Reyjohn

Reputation: 2733

How to sort a customized listview alphabatically?

I have a customlist view with an ImageView and a textview. I am retrieving that list view by this method:

private List<Currency> getModel() {
        List<Currency> list = new ArrayList<Currency>();
        for (int i = 0; i < countryCode.length; i++) {

            list.add(get(countryCode[i], flag[i]));
        }


        return list;
    } 

this method returns a list of an image and a textview in a particular list item, and I am setting this in a adapter to show it in a listview. But how can I sort this list by alphabetically comparing with the text of that text view in the list? I have tried this

Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareToIgnoreCase(s2);
        }
    });

but this method only works for string types list, but my list is not in string type? What to do?

Upvotes: 1

Views: 227

Answers (3)

npe
npe

Reputation: 15719

Your list contains Currency objects, so you will need to create a comparator that compares Currency. Now, I am not sure what kind of Currency class are using, but if it is the one from the standard JDK, then it has a getCurrencyCode() method that returns a string (or you can use the countryCode you're passing into get() invocation).

Then, you just create a Comparator instance like this:

Collections.sort(list, new Comparator<Currency>() {
    @Override
    public int compare(Currency s1, Currency s2) {
        return s1.getCurrencyCode()
                 .compareToIgnoreCase(s2.getCurrencyCode());
    }
});

Note, that the return clause does not have to do the string comparison. What you have to do is basically return a value that is less than zero if you think s1 is "smaller" than s2, or a value that is greater than zero, if you think it's "greater" than s2 (or return zero if they are equal). The comparison algorithm is up to you.

Upvotes: 0

nullpotent
nullpotent

Reputation: 9260

Collections.sort(list, new Comparator<Currency>() {
        @Override
        public int compare(Currency s1, Currency s2) {
            return s1.compareTo(s2); 
        }
});

Don't forget to implement Comparable<Currency> interface in order to implement the compareTo(Currency o); the way you want it.

Upvotes: 1

nazlo
nazlo

Reputation: 431

Try to compare in this way

Collections.sort(list, new Comparator<Currency>() {
        @Override
        public int compare(Currency c1, Currency c2) {
            return c1.getCurrencyName().compareToIgnoreCase(c2.getCurrencyName());
        }
    })

Upvotes: 2

Related Questions