stanna stanna - 1 year ago 73
Android Question

How to do a SQLDatabase Contains search in android

As far as I'm aware of the character

is used as a placeholder and it will be replaced with the value that you pass in the
string array.

This is my code for the query:

String whereClause = null;
String[] whereArgs = null;
if (search != "") {
whereClause = InventoryEntry.COLUMN_INVENTORY_ITEM_NAME +
whereArgs = new String[]{search};

Cursor cursor = db.query(InventoryEntry.TABLE_NAME,

When I go to execute the query I get the following error:

android.database.sqlite.SQLiteException: near "CONTAINS": syntax error (code 1): , while compiling: SELECT * FROM items WHERE itemName CONTAINS(itemName,?) ORDER BY date ASC

What do I need to change so that my query will be in the form of:

SELECT * FROM items WHERE itemName CONTAINS(itemName,`search`);

Also, is it proper practice to use CONTAINS over LIKE?

Thank you!

Answer Source

SQLite does not have a CONTAINS keyword, use LIKE.

Something like this:

whereClause = InventoryEntry.COLUMN_INVENTORY_ITEM_NAME +
        " LIKE " + InventoryEntry.COLUMN_INVENTORY_ITEM_NAME +
        " OR " + InventoryEntry.COLUMN_INVENTORY_ITEM_NAME +
        " LIKE ?";
whereArgs = new String[]{search};

Also, do not compare strings with the != operator, use the equals() method instead, or do something like this:

if (search.length() > 0) {
    // ...

The != operator checks for reference equality when comparing objects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download