user3320669
user3320669

Reputation:

Getting the correct contact name by phone number

I am trying to get the correct contact name from a phone number to display it into a ListView.

But I am getting every time only the same Contact Name for all phone numbers...

Here is my code:

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);
}

I can't find where is my error... and only get the same name for all senders numbers.

Thank you

Upvotes: 0

Views: 142

Answers (1)

Simon
Simon

Reputation: 11190

Here is the correct code for your function.

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;
}

Upvotes: 1

Related Questions