I am making an application which search messages in the inbox based on sender number. Here is my code:
public void onClick(View v)
{
Toast.makeText(this,
I also had this problem in my code, and it took me a while to find the correct answer. What worked for me is what @Arushi gupta wrote in his reply.
Here's my working code, adapted so that the user may perform EXACT search queries or search for values containing the words in the query (AND operator or OR operator). My code uses a CursorLoader, but it's the same as using a ContentResolver for this example:
String selection = myDbContract.myDbEntry.getSelectionForGivenKeywordsAndOperator(requested_keyword, "OR"); //Can write "EXACT" / "AND" / "OR"
return new CursorLoader(this, myQueryUri, MY_TABLE_ELEMENTS, selection, null, null);
And here is the selection method in the dB contract:
public static String getSelectionForGivenKeywordsAndOperator(String keyword_list, String operator) {
String returnSQLCommand = null;
if(keyword_list.length()==0) return returnSQLCommand;
switch (operator) {
case "EXACT":
returnSQLCommand = COLUMN_KEYWORD + "='" + keyword_list + "'";
break;
default: //operator is "AND" or "OR"
List keywords = new ArrayList<>();
if (keyword_list.contains(" ")) keywords = Arrays.asList(keyword_list.split(" "));
else if (keyword_list.contains(",")) keywords = Arrays.asList(keyword_list.split(","));
else if (keyword_list.contains(";")) keywords = Arrays.asList(keyword_list.split(";"));
else if (keyword_list.contains(".")) keywords = Arrays.asList(keyword_list.split("."));
else keywords.add(keyword_list);
returnSQLCommand = "'%" + keywords.get(0) + "%'";
if (keywords.size()>=1) {
returnSQLCommand = COLUMN_KEYWORD + " LIKE '%" + keywords.get(0) + "%'";
for (int i = 1; i < keywords.size(); i++) {
returnSQLCommand = returnSQLCommand + " " + operator + " " + COLUMN_KEYWORD + " LIKE '%" + keywords.get(i) + "%'";
}
}
break;
}
return returnSQLCommand;
}
I verified that this code works as planned, you're welcome to try it.