Search code examples
sqldatabasesqlitedictionaryandroid-sqlite

convert qb.query to rawQuery?


I want to write a query that will search through the database and give all items in which words start with the search word. For example, if I search RULE word it must search the database and find all words in the sentence which contain RULE.

This one but Cursor cursor = qb.query(db,sqlSelect, "Japanese LIKE ?",new String[] will search only one column. ("Japanese" column)

so I'm trying to convert qb.query to rawQuery but not working at all.

public List<Dict> getDictByJapanese(String name)
    {
        SQLiteDatabase db = getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        String[] sqlSelect={"Id","Japanese","Yomikata","Thai","English"};
        String tableName="Dicts";

        qb.setTables(tableName);
        Cursor cursor = qb.query(db,sqlSelect, "Japanese LIKE ?",new String[]{"%"+name+"%"},null,null,null);
        List<Dict> result = new ArrayList<>();
        if(cursor.moveToFirst())
        {
            do{
                Dict dict = new Dict();
                dict.setId(cursor.getInt(cursor.getColumnIndex("Id")));
                dict.setJapanese(cursor.getString(cursor.getColumnIndex("Japanese")));
                dict.setYomikata(cursor.getString(cursor.getColumnIndex("Yomikata")));
                dict.setThai(cursor.getString(cursor.getColumnIndex("Thai")));
                dict.setEnglish(cursor.getString(cursor.getColumnIndex("English")));

                result.add(dict);
            }while (cursor.moveToNext());
        }
        return result;
    }

I tried to modify the code as below but...

Cursor cursor = qb.query(db,sqlSelect, "Japanese LIKE ?"+"Yomikata LIKE ?",new String[]{"%"+name+"%"},null,null,null);

Thanks in advance.


Solution

  • You can still use query() by adding conditions to the existing sql statement like this:

    String conditions = "Japanese LIKE ? OR Yomikata LIKE ? OR Thai LIKE ? OR English LIKE ?";
    String par = "%"+name+"%"; 
    Cursor cursor = db.query(tableName, sqlSelect, conditions, new String[]{par, par, par, par}, null, null, null);
    

    I used the logical operator OR in the conditions because I assumed that this is what you want, you can change it to AND if this is your requirement.