Reputation: 338
when I want to search for a user in my database using room query, I have to enter the full name to get the result. How can I search in database letter by letter?
@Query("SELECT * FROM database WHERE name LIKE :search")
fun find(search:String?):List<User>
Upvotes: 1
Views: 2958
Reputation: 2375
For search in such a way, with you entering "K" and "Kourosh" showing up, you can use a code like this:
This makes the words being searched letter by letter.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY " + ENGLISH + " LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
// this is the main thing
cursor = db.rawQuery(sql, new String[]{"%" + englishWord + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String english = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Bean(id, english, bangla, status));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
Upvotes: 1
Reputation: 3830
Try
@Query("SELECT * FROM database WHERE name LIKE :search")
fun find(search:String?):List<User>
search = "%Kourosh%";
find(search);
//OR
@Query("SELECT * FROM database WHERE name LIKE '%' || : arg0 || '%'")
fun find(search:String?):List<User>
Upvotes: 6