1

I want to sort a list of custom objects in descending order with respect to its one property (with a variable type "long") in android. For this, I used Collections Comparator but my problem is it says "Long.compare call requires API level 19 (current min is 16)" Is there any alternative way to handle this? (The code runs perfectly on my virtual device it gives no error but I want it to run on devices with API level below 19)

My sorting code is:

// Sort the news according to their last update time (show the latest on top)
    Collections.sort(news, new Comparator<NewsItem>() {
        @Override
        public int compare(NewsItem newsItem1, NewsItem newsItem2) {
            return Long.compare(newsItem2.getUpdateTime(), newsItem1.getUpdateTime());
        }
    });

my custom object is NewsItem with five attributes and I want to sort the list wrt to the UpdateTime attribute which is of the Long type.

1 Answer 1

1

You could create Long objects for the times and compare them directly:

Collections.sort(news, new Comparator<NewsItem>() {
    @Override
    public int compare(NewsItem newsItem1, NewsItem newsItem2) {
        return Long.valueOf(newsItem2.getUpdateTime()).compareTo(
               Long.valueOf(newsItem1.getUpdateTime()));
    }
});

As a side note - API level 16 is quite outdated, and you may want to consider upgrading your requirements.

Sign up to request clarification or add additional context in comments.

1 Comment

It was advised that to support much devices, keep the minSdkLevel to low, so I choose API level 16, but I can increase it. Thanks for the answer Mureinik.

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.