I am working on android project and I need to perform a like query in SQLITE i.e.
SELECT * FROM table WHERE column LIKE %value%.
Below is the code I am using to try and build up the query.
myDB = context.openOrCreateDatabase("PasswordManager", Context.MODE_PRIVATE, null);
String[] columns = new String[]{"*"};
if (searchType == SearchType.App)
{
where = "appName like ?";
}
else if (searchType == SearchType.Username)
{
where = "username like ?";
}
else if (searchType == SearchType.Name)
{
where = "company like ?";
}
String[] args = {"%" + searchTerm + "%"};
cursor = myDB.query("password", columns, where, args, null, null, null);
For some reason this doesn’t return any results if I try and search for a pattere but If I search for the whole string it finds something. For example, if I have the value Hello World and perform a search for Hello, nothing comes back, if I do a search for Hello World then I get a result.
I can’t see why this wouldn’t work. I’ve tried adding and removing the % symbols from around the search term but didn’t make any difference.
Thanks for any help you can provide.
UPDATE
I’ve tried what dymmeh said but this doesn’t seem to have worked. Below is the code I have tried.
myDB = context.openOrCreateDatabase("PasswordManager", Context.MODE_PRIVATE, null);
String[] columns = new String[]{"*"};
if (searchType == SearchType.App)
{
where = "appName like %" + searchTerm + "%";
}
else if (searchType == SearchType.Username)
{
where = "username like %" + searchTerm + "%";
}
else if (searchType == SearchType.Name)
{
where = "company like %" + searchTerm + "%";
}
//String[] args = {"%" + searchTerm + "%"};
cursor = myDB.query("password", columns, where, null, null, null, null);
Using the code above now crashes the app, I’ve tried surrounding the the % searchTerm % in single quote marks, and this stops the app crashing but I get the original problem that if I search for the exact string, a result is found if I search for part of the string, I don’t get any results.
Don’t use the select arguments when using
like..Instead just do
And just pass
nullfor yourargs