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,
There is two joker : "%" and "_".
"%" is replacing any string (multiple characters),
"_" is replacing one (and only one) character.
For example :
LIKE 'B%'
let you find everything which starts with "B". (like "BATMAN");
LIKE '%B%'
let you find everthing which contains "B". (like "ABBA");
LIKE'_B%'
let you find everything which contains ONE caracter, then a "B". (like "ABERCROMBIE)".
if you want to retrieve a string which contains "%" or "_", you may use an escape caracter :
LIKE '%#_B%' ESCAPE #
let you find any strings which contains one "_" followed by a "B". (like "TEST_BATMAN").
I hope that helped.
Al_th
Try following EDITED:
String[] argList = {"'%%%%"+searchtxt.getText().toString()+"%%%%'"};//TRY THIS
^^^^ ^^^^ // TRY THIS
Uri smsUri = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(smsUri, colList, "address LIKE ?", argList, "DATE");
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<String> 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.