Home » Android » java – Android sqlite query to match column containing text

java – Android sqlite query to match column containing text

Posted by: admin May 14, 2020 Leave a comment

Questions:

Trying to make a query that will return a match if the given column contains the text anywhere inside. For instance if I were to pass the word “really” a column containing the text “This is a really long line of text” would match. So far my queries only return if it matches exactly so it would only match a column containing “really” and that is it.

I’ve tried a couple ways but both seem to return the same result:

First way (s is the string I’m passing in):

    Cursor cursor = mDb.query(DATABASE_TABLE, new String[] {KEY_TITLE}, KEY_TITLE + " LIKE '%" + s + "%' COLLATE NOCASE", null, null, null, null);

Next way

String p_query = "SELECT COUNT(*) FROM data WHERE number=? COLLATE NOCASE";
How to&Answers:

Trying to make a query that will return a match if the given column contains the text anywhere inside.

This works for me and it’s parameterized:

Cursor cursor = mDb.query(DATABASE_TABLE, new String[] {KEY_TITLE}, 
        KEY_TITLE + " LIKE ?", new String[] {"%" + s + "%"}, 
        null, null, null);

“Really” is a distinct enough word, but if you are searching for something like “ice” and don’t want “dice”, “vice”, “icecream”, etc you’ll have to use different patterns like: "% " + s + " %" and s + " %".

Or use an FTS table with a tokenizer, like Porter Stemming.