通过电话号码获取正确的联系人姓名

时间:2014-02-17 20:19:44

标签: android

我正在尝试从电话号码中获取正确的联系人姓名,以将其显示为ListView

但我每次只获得所有电话号码的相同联系人姓名......

这是我的代码:

private String getContactName(String string){
    String name=null;

    ContentResolver cr=getContentResolver();
    Cursor cur=cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);

    if(cur.getCount()>0){
        while(cur.moveToNext()){
            String id=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            name=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }

    }
    return name;
}


public void onClick(View v)
{
    ContentResolver contentResolver=getContentResolver();
    Cursor cursor=contentResolver.query(Uri.parse("content://sms/inbox"),null,null,null,null);

    int indexBody=cursor.getColumnIndex(SmsReceiver.BODY);
    int indexAddr=cursor.getColumnIndex(SmsReceiver.ADDRESS);

    //  int indexAddr = Integer.parseInt(getContactName(Integer.toString(cursor.getColumnIndex( SmsReceiver.ADDRESS ))));

    //getContactName(Integer.toString(indexAddr));
    ////

    if(indexBody<0||!cursor.moveToFirst())return;

    smsList.clear();

    do
    {
        //String str = "Sender: " + cursor.getString( indexAddr ) + "\n" + cursor.getString( indexBody );
        String str="Sender: "+getContactName(cursor.getString(indexAddr))+"\n"+cursor.getString(indexBody);
        smsList.add(str);
    }
    while(cursor.moveToNext());


    ListView smsListView=(ListView)findViewById(R.id.SMSList);
    registerForContextMenu(smsListView);

    smsListView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,smsList));
    smsListView.setOnItemClickListener(this);
}

我找不到我的错误在哪里...并且只为所有发件人号码获取相同的名称。

谢谢

1 个答案:

答案 0 :(得分:1)

以下是您的功能的正确代码。

private String getContactName(String phoneNumber)
{
    String name = null;
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
        Uri.encode(phoneNumber)), new String[]{ PhoneLookup.DISPLAY_NAME }, null, null, null);
    if(cur != null){
        try{
            if(cur.getCount() > 0){
                if(cur.moveToFirst()){
                    name = cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME));
                }
            }
        }
        finally{
            cur.close();
        }
    }
    return name;
}