SQLite how to order from highest to lowest?

3

I would like to know how I can do a ORDER BY or order the query ascendingly, this is the code I tried but it sends me an error that the application has stopped.

public Cursor readData() {
    String[] allColumns = new String[] { DatabaseHelper.IDs,
            DatabaseHelper.MSG };
    Cursor c = database.query(DatabaseHelper.TABLE_NAME, allColumns, null,
            null, null, null, null, DatabaseHelper.IDs+" ASC");
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}
    
asked by JESUS ESPINOSA 02.02.2016 в 14:59
source

2 answers

2

There is a problem in the order of the parameters. The signature of the method is:

query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

... but the% ordination% co in the String parameter is being passed instead of using the limit parameter.

    
answered by 02.02.2016 / 16:04
source
2

According to the official Android documentation (in English), there are four different types of query:

  • query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
  • query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
  • query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
  • query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

In your particular case, you are using:

database.query(DatabaseHelper.TABLE_NAME, allColumns, null,
        null, null, null, null, DatabaseHelper.IDs+" ASC");

that would correspond to the first case above (with 8 parameters). So the problem is that you are passing the ordination parameter in the place where the limit corresponds (it should be the seventh, but it appears in eighth place).

The solution would be to change the order of the last two parameters to fit the first case, or to eliminate one of the null (and it would be adjusted to the third case):

Cursor c = database.query(DatabaseHelper.TABLE_NAME, allColumns, null,
        null, null, null, DatabaseHelper.IDs+" ASC", null);

or

Cursor c = database.query(DatabaseHelper.TABLE_NAME, allColumns, null,
        null, null, null, DatabaseHelper.IDs+" ASC");
    
answered by 02.02.2016 в 16:04