1

What would be the android room query to match a column data exactly match or start with the search string

VVV this seems to giving me only the exact match

select * from table where dna_sequence like :searchTerm

Thanks

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Big O
  • 417
  • 1
  • 5
  • 14
  • I think it reference to: https://stackoverflow.com/questions/44184769/android-room-select-query-with-like. You can check it. – dinhlam May 22 '20 at 05:40
  • I've written an answer below. If you need more help, we need to see your Entity and DAO classes. The problem is in your Java or Kotlin code and the value being passed to `searchTerm`. The SQL query is exactly correct. – Code-Apprentice May 22 '20 at 05:47

2 Answers2

2

Try this in search method:

public String getResultForSearchString(String searchTerm){
String searchExptression=searchTerm+"%";
//.. perform search operation on SQLite with searchExpression
return result;
}

For more information visit: https://www.sqlitetutorial.net/sqlite-like/

Hope it helps.

Csongi77
  • 329
  • 3
  • 13
2

this seems to giving me only the exact match

select * from table where dna_sequence like :searchTerm

There is nothing wrong with your query. The problem is with your Java or Kotlin code. You are getting an exact match because you are passing an exact to searchTerm and not using any wildcards. The LIKE operator in SQL allows us to use wildcards in the string to match more than just strict equality. _ will match a single character while % will match zero or more characters. If you don't use these wildcards, then LIKE will be the exact same as =. So you need to pass a value for searchTerm that uses one of these wild card characters. For example, if you a DAO interface declared as

@Dao
public interface MyDao {
    @Query("SELECT * FROM foo WHERE search like :searchTerm")
    public Foo[] getFooSearch(String searchTerm);
}

You can call the method with something like:

MyDao dao;
dao.getFooSearch("abcdef%");

which will match the start of the string.

Note: This example is a bit contrived because you only provided your SQL query and didn't provide any of the Java or Kotlin code for your DAO or Data Entity.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268