2012-01-09 4 views
2

の番号から連絡先の名前を取得する2.3.4 Androidの番号を使用して連絡先の名前を取得しようとしましたが、動作していませんでした。ここに私のコードが添付されています。親切..私はスタックに掲載さエミュレータでは、流れの上にその作業を非常に多くの方法を試みたが、電話でのラン..Android 2.3.4

String[] projection = new String[] { Contacts.Phones.DISPLAY_NAME, 
            Contacts.Phones.NUMBER }; 

// encode the phone number and build the filter URI 
Toast.makeText(context, "sender: "+sender, Toast.LENGTH_LONG).show(); 

Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, 
             Uri.encode(sender)); 

// query time 
Cursor c = context.getContentResolver().query(contactUri, projection, null, 
               null, null); 

// if the query returns 1 or more results 
// return the first result 
if(c.getCount()>0){ 
    if (c.moveToFirst()) { 
     name = c.getString(c.getColumnIndex(Contacts.Phones.DISPLAY_NAME)); 
    }     
}else{ 
    name="UnKnown"; 
} 
+0

完全なコードを投稿してください。 – swathi

答えて

4

Contacts.Phones.NUMBERのためにAPIを見ながら失敗してきた支援:

公衆static final String NUMBER

ユーザーが入力した電話番号です。

ですから、プログラムで使用する番号は、電話帳内の1つのようまったく同じ(文字単位)を指定する必要があります。あなたの電話帳に+46xxxxxxxxのような国別コード情報が含まれている可能性があるため、これは電話で失敗する理由かもしれません。番号が同じであれば、それは確認するために、アルゴリズムを使用しますContactsContractからPhoneLookupを使用してこの問題を回避するには

(また、Contacts.Phonesから 定数は推奨されません):

public static String getContactName(String num, ContentResolver cr) { 

    Uri u = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI Uri.encode(num)); 
    String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME}; 

    Cursor c = cr.query(u, projection, null, null, null); 

    try { 
     if (!c.moveToFirst()) 
      return number; 

     int index = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); 
     return c.getString(index); 

    } finally { 
     if (c != null) 
      c.close(); 
    } 
} 

(このコードが返されますその番号の連絡先が見つからない場合は番号を入力してください)。

+0

@dacweさん、ありがとうございました。:-) – jerith

+0

うまくいっています.... – jerith

+0

アダプターから 'ContentResolver cr''をどうやって渡すか?? – cheloncio

0

カーソルローダーを使用すると、メインスレッドをブロックできなくなります。索引を取得してから文字列を取得するのは大変です。

private String getContactName(String num) { 

    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(num)); 
    String[] projection = new String[] {ContactsContract.Contacts.DISPLAY_NAME}; 

    CursorLoader cursorLoader = new CursorLoader(getActivity(), uri, projection, null, null,null); 

    Cursor c = cursorLoader.loadInBackground(); 

    try { 
     if (!c.moveToFirst()) 
      return num; 

     return c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
    } catch (Exception e) 
    { 
     Log.e(TAG,"Error looking up the contactname." + e); 
     return num; 
    } 
    finally { 
     if (c != null) 
      c.close(); 
    } 
} 
関連する問題