Filter by dates with rawQuery


I can not filter by end date on an SQLite.

For this I have created a method which is passed 2 dates, one start and one end.

private void consultListaDietas (Date di, Date df) {

    SQLiteDatabase db =conn.getReadableDatabase();
    Dieta dieta=null;
    Date date = new Date();
    Cursor cursor = db.rawQuery("SELECT * FROM "+Utilidades.TABLA_DIETAS,null);
    if (di==null && df==null){
        while (cursor.moveToNext()){
            dieta = new Dieta();
            String fecha = cursor.getString(3)
            DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                date = iso8601Format.parse(fecha);
            } catch (ParseException e) {
                Log.e(TAG, "Parsing ISO8601 datetime failed", e);


        Date[] args = new Date[]{di,df};
        cursor = db.rawQuery("SELECT * FROM "+Utilidades.TABLA_DIETAS + " WHERE BETWEEN di AND df",args);

I have the problem in the else, in the args I get an error "Wrong 2nd argument type". I have verified that both the argument di and df are Date arguments. I guess I have a problem in my practice.

Thanks in advance !!

asked by Raúl Cuc 25.12.2018 в 13:44

1 answer


The signature of the rawQuery method that you are using is rawQuery(String sql, String[] selectionArgs) , therefore the second parameter must be a vector of String not of Date .

di and df , are not defined in the code but I assume that they are Date , they should be soformed to String of the form "yyyy-MM-dd HH:mm:ss" to be used in the query.

The query has two errors:

1) The date field of the table is missing before BETWEEN
2) The values to be replaced are marked with a question mark.

DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDi = iso8601Format.format(di);
String strDf = iso8601Format.format(df);
String[] args = new String[]{strDi,strDf};
cursor = db.rawQuery("SELECT * FROM "+Utilidades.TABLA_DIETAS + " WHERE <CAMPO FECHA DE LA TABLA> BETWEEN ? AND ?",args);
answered by 25.12.2018 / 14:55