1

I wish to sort my listView by the variable called score. Anybody know how to do this? Currently here is my code that get's information from a database and displays it in a list view.

 List<String> queryTable(){
    List<String> player = new ArrayList<String>();

    SQLiteDatabase db = myOpenHelper.getReadableDatabase();
    Cursor cursor = db.query(CustomOpenHelper.TABLE_NAME, null, null, null, null, null, null);

    while (cursor.moveToNext()) {
        int id = cursor.getInt(cursor.getColumnIndex("_id"));
        String name = cursor.getString(cursor.getColumnIndex("name"));
        int score = cursor.getInt(cursor.getColumnIndex("score"));
        player.add(id + " --> the player " + name + " has got a score of " + score +"s");
    }

So how would I go about sorting this listview by the variable "score"? Thanks guys.

2
  • try it using comparable Commented Sep 29, 2014 at 6:38
  • get the information from database already sorted. There's sql keywords for this ORDERY BY columnname You can add ASC or DESC to get it ascending or descending Commented Sep 29, 2014 at 6:40

4 Answers 4

1

Last parameter of the query function is used to sort. Just replace null with

column_name + " DESC".
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry it doesn't seem to work it just crashes when I implement this.
0

List has sort functionality for elements. This is the sample code:

List<Fruit>  fruits= new ArrayList<Fruit>();
Fruit fruit;
for(int i=0;i<100;i++)
{
   fruit = new fruit();
   fruit.setname(...);
   fruits.add(fruit);
}
//Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
    @Override
    public int compare(Fruit  fruite1, Fruit  fruite2)
    {

        return  fruite1.fruitName.compareTo(fruite2.fruitName);
    }
});

This code sorts the list according to furitName property. When we look your code, you can do the same thing. Firstly, you have to use a class that represents the id,name and score. Using this class, you can add and sort elements using List.

Comments

0

Just store the records in a list and then apply sorting(depending on your variable called score) and then notify the list with this updated and sorted list.

Comments

0

call this method:

Collections.sort(score_list, myComparator);

here is your comparator:

Comparator myComparator = new Comparator() {

    @Override
    public int compare(Integer lhs, Integer rhs) {
        int i1 = lhs;
        int i2 = rhs;
        return (i1 -i2);
    }
};

Comments

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.