Adam Varhegyi
Adam Varhegyi

Reputation: 9894

Searching SQLite database inside Android app

I got a searching function inside my app. It works almost properly, my problem is it is only catching results that similiar to the searchWord from the begining.

For example: If searchWord is "ada", the results will be contains all the records that START WITH "ada" but not those that contains "ada" somewhere inside them.

I know it must be just a little modification but this is the first piece of database handling i ever did.

So how must i modify this to search for any contains, and not for starts with?

code:

public Cursor getMatchingFromContacts(String searchWord) throws SQLException {

    String queryString = "SELECT _id, full_name FROM "
            + SF_CONTACT_TABLE;

    if (searchWord != null) {
        searchWord = searchWord.trim() + "%";
        queryString += " WHERE " + FULL_NAME + " LIKE ?";
    }
    String params[] = { searchWord };

    if (searchWord == null) {
        params = null;
    }
    try {
        Cursor cursor = db.rawQuery(queryString,
                params);
        if (cursor != null) {
            cursor.moveToFirst();
            return cursor;
        }
    } catch (SQLException e) {
        Log.e("AutoCompleteDbAdapter", e.toString());
        throw e;
    }

    return null;
}

Upvotes: 0

Views: 137

Answers (2)

Deepzz
Deepzz

Reputation: 4571

Try this..

if (searchWord != null) 
{
    searchWord = "%" + searchWord + "%";
    queryString += " WHERE " + FULL_NAME + " LIKE ?";
}

Upvotes: 2

Yury
Yury

Reputation: 20936

Just modify your block here:

if (searchWord != null) {
    searchWord = "%" + searchWord.trim() + "%";
    queryString += " WHERE " + FULL_NAME + " LIKE ?";
}

Upvotes: 3

Related Questions