Search code examples
androidsqliteandroid-sqlite

SQLite: Select using LIKE '%?%' with rawQuery


I am trying to use a select statement to query some data from the database's table . when i type =? the query succeed , but when i use LIKE %?% instead i got this error in logcat:

FATAL EXCEPTION: main
Process: com.example.ahmed.bus_time_djerba4, PID: 4178
java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range.  The statement has 0 parameters.

and this is my methode that call the database:

public String  QuerySQL(String DepartStation,String Destination){

    String result="";

    SQLiteDatabase db=this.getReadableDatabase();
    Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE '%?%' and "+Col_4+" LIKE '%?%'", new String[]{DepartStation,Destination});

    if(c.getCount()==0) {result="Data not found";c.close();}
    else {
        while (c.moveToNext()) {
            //affichage des lignes
            int ligne = c.getInt(1);
            String Station = c.getString(2);
            String Dest = c.getString(3);
            String hours = c.getString(4);
            result += "\n" + ligne + "|" + Station + "-" + Dest + " " + hours;
        }
        c.close();
    }

    return result;
}

what is the problem ? please


Solution

  • The Problem is with the SQL query you have used.
    you are giving ? A String which is not acceptable for prepare statements. select distinct * from table_name where X like '%?%'; is not correct because ? will be a string with double quotation inside a quotation like '%"your_string"%'.

    instead write:

    select distinct * from table_name where X like ?;
    

    and for ? use "'%your_string%'". you can apply this to your array of string too.