Home » Android » android – data type mismatch error when using ORDER BY

android – data type mismatch error when using ORDER BY

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’ve got an android app using a local sqlite database.

private SQLiteDatabase mDb;

when I run this query I get my Cursor over rows with pid equal to id, as desired:

mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID}, 
    KEY_PID+" = "+id, null, null, null, null, null);        

when I run the following query, aiming to get that same result set, ordered by pid I get “android.database.sqlite.SQLiteException: datatype mismatch

mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID}, 
    KEY_PID+" = "+id, null, null, null, null, KEY_PID+" DESC");

Any ideas?

How to&Answers:

It looks like you got just a little mixed up. According to the SQLiteDatabase.query documentation, the last argument is the LIMIT clause. The second to last is the ORDER BY clause.

Cursor query (boolean distinct, 
            String table, 
            String[] columns, 
            String selection, 
            String[] selectionArgs, 
            String groupBy, 
            String having, 
            String orderBy, // <-- ORDER BY
            String limit)

EDIT

But, there is also another SQLiteDatabase.query where ORDER BY would be last

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

Answer:

This worked for me

String filter = MySQLiteHelper.JOB_ID + "=" + Integer.toString(jobID);
String orderBy =  MySQLiteHelper.LOG_TIME + " DESC";
Cursor cursor = database.query(MySQLiteHelper.LOG_TABLE_NAME, logTableColumns,
        filter, null, null, null, orderBy);

Answer:

KEY_PID + " = " + "'" + id + "'"

Answer:

Since Orderby is the second last parameter in the query;
your query would be like this

mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID}, 
    KEY_PID+" = "+id, null, null, null, KEY_PID+" DESC", null);

Answer:

If I correctly understood your problem, try this.

    String[] columns = new String[] {KEY_PID, KEY_TID};
    String where = KEY_PID + " = " + Integer.toString(id);
    String orderBy = KEY_PID + " DESC";

    Cursor cursor = mDb.query(PT_TABLE, columns, where, null, null, null, orderBy);