Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort rows using SQLite in Android with a rawquery method?

I'm using the following method to get data from a table:

Cursor c = ourDatabase.rawQuery("SELECT " + KEY_SWIMMERLAPS + " * "
  + KEY_SPONSOR + " AS result FROM " + DATABASE_TABLE, null);

I was wondering if this can be edited to sort the results by KEY_SWIMMERLAPS. I thought the following would work:

Cursor c = ourDatabase.rawQuery("SELECT " + KEY_SWIMMERLAPS + " * "
  + KEY_SPONSOR + " AS result FROM " + DATABASE_TABLE, KEY_SWIMMERLAPS + " DESC");

However, I get an error because KEY_SWIMMERLAPS is not a string:

The method rawQuery(String, String[]) in the type SQLiteDatabase is not applicable for the arguments (String, String)

like image 293
Sheldon Avatar asked Feb 12 '26 15:02

Sheldon


1 Answers

You used the second argument on the rawQuery method and expected to be used as an order clause. That is not the case. The second argument is used to provide values for ? placeholders in your SQL query string. Using the following should do the trick:

Cursor c = ourDatabase.rawQuery("SELECT " + KEY_SWIMMERLAPS + " * "
            + KEY_SPONSOR + " AS result FROM " + DATABASE_TABLE + " ORDER BY "+ KEY_SWIMMERLAPS+" DESC", null);
like image 83
Pierre Avatar answered Feb 15 '26 05:02

Pierre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!