2012-04-16 68 views
0

我想从联系人名称中检索电话号码。所以我有这个代码在SQLite中用字符串查询

public String getPhoneNumber(String name) { 
    String phonenumber = ""; 
    ContentResolver cr = getContentResolver(); 
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, 
      "DISPLAY_NAME LIKE '%" + name + "%'", null, null); 
    if (cursor.moveToFirst()) { 
     String contactId = cursor.getString(cursor 
       .getColumnIndex(ContactsContract.Contacts._ID)); 
     // 
     // Get all phone numbers. 
     // 
     Cursor phones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID 
       + " = " + contactId, null, null); 
     while (phones.moveToNext()) { 
      String number = phones.getString(phones 
        .getColumnIndex(Phone.NUMBER)); 
      int type = phones.getInt(phones.getColumnIndex(Phone.TYPE)); 
      switch (type) { 
      case Phone.TYPE_HOME: 
       //phonenumber = number; 
       // do something with the Home number here... 
       break; 
      case Phone.TYPE_MOBILE: 
       phonenumber = number; 
       // do something with the Mobile number here... 
       break; 
      case Phone.TYPE_WORK: 
       //phonenumber = number; 
       // do something with the Work number here... 
       break; 
      } 
     } 
     phones.close(); 
     // 
     // Get all email addresses. 
     // 

    } 
    cursor.close(); 
    return phonenumber; 
} 

但是,如果联系人名称与db中的名称完全不匹配,它将不会返回任何内容。因此,即使输入名称不太可能,是否有任何方法来检索电话号码?

例如,有一个联系人:原型Alex和我的输入名称是:prototype或alex。

+0

''Prototype Alex'LIKE'%prototype%''是真的(如果这是有效的语法) – zapl 2012-04-16 13:36:38

回答

0

这不是您的具体问题的答案,但它可能会有所帮助。有像Levenshtein距离,soundex或metaphone approximate string matching算法。 也许它可能是您的一个选择,从内容提供商获取所有联系人,然后使用其中一种算法进行搜索。

+0

感谢队友:D,我会试试这个! – 2012-04-16 13:48:15

+0

我发现另一个问题!,如果联系人的名称是“Ân”(unicode字符),那么我尝试用“â”或“Ân”查询,返回数据为null。但是,如果我返回数据是正确的使用“=”而不是“like”。所以我该怎么做 ? – 2012-04-16 13:58:08