Search code examples
javaandroidsqliteandroid-studioandroid-sqlite

Why is my SQLite select query not working in app but working on Database Inspector on Android Studio?


I am trying to retrieve records from my SQLite DB on Android but somehow it's not working. The query works fine without the where clause in the app and with the where clause in the database inspector.

  • The table schema is correct.
  • The date format in the database and the query is the same.

Here is my code snippet:

public ArrayList<String> retrieveFunc() {

        ArrayList<String> array_list = new ArrayList<String>();
        SQLiteDatabase db = this.getReadableDatabase();
        String date = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
        Cursor res =  db.rawQuery( "select score from stats WHERE date = "+date,null);
        res.moveToFirst();
        Log.d("Res count",res.getCount()+"");

        while(!res.isAfterLast()){
            Log.d("In while","in while");
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_SCORE)));
            res.moveToNext();
        }
        return array_list;
    }

Solution

  • After struggling with this issue for a few hours, I found the fix minutes after posting this question.

    I changed the query from

    Cursor res =  db.rawQuery( "select score from stats WHERE date = "+date,null);
    

    to

    Cursor res =  db.rawQuery( "select score from stats WHERE date = ?  ",new String[]{ date });
    

    Passing the value through selection args worked for me rather than concatenating it with the query.