I am building a voice assistant for android, here this method retrieves contact names one by one and compares it to to SpeechToText input.
I am successfully getting the contact names, but when I am comparing it with my input text, nothing is happening.
Here is the code
private void callFromContact(String text_received, int index){
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(text_received.toLowerCase().contains(name)){
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNames.add(name);
contactNumbers.add(phoneNumber);
}
}
Here for example I sending "call karan" as input, while debugging the name "Karan" comes up as the value of name variable, but when comparing it in if-statement, nothing happens, I mean the next statement is not executed, what might be the problem, help would be appreciated.
您还需要将name
变量转换为小写,因为String.contains()
方法区分大小写,所以call karan
不包含Karan
。
if you just want to compare 2 strings, no matter if they are lower or upper case you should use equalsIgnoreCase . in your case:
if (text_received.equalsIgnoreCase(name))
{
//...
}
EDIT: according to Bohuslav Burghard comment if you need to search a specific part of the string and make it ignore case, you can use regular expression with match function:
if (text_received.matches("(?i:.*" + name + ".*)"))
{
//...
}
i used this method and it worked well. match() did not fullfiled my needs neither equal() nor equalToIgnore...
public static boolean containsIgnoreCase(String src, String what) {
final int length = what.length();
if (length == 0)
return true; // Empty string is contained
final char firstLo = Character.toLowerCase(what.charAt(0));
final char firstUp = Character.toUpperCase(what.charAt(0));
for (int i = src.length() - length; i >= 0; i--) {
// Quick check before calling the more expensive regionMatches() method:
final char ch = src.charAt(i);
if (ch != firstLo && ch != firstUp)
continue;
if (src.regionMatches(true, i, what, 0, length))
return true;
}
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.