从名称获取android中的联系号码

时间:2015-02-13 07:01:21

标签: android eclipse

我是android开发的新手,我试图通过名称获取联系号码

这里我的代码

String contname = "Sachin";
    Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, contname);        
    ContentResolver contentResolver = getContentResolver();
    String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
    String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;

    Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
    while (idCursor.moveToNext()) {
        String id = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
        String contact_id = idCursor.getString(idCursor.getColumnIndex( id ));

        String key = idCursor.getString(idCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        String name = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        String HAS_PHONE_NUMBER=idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
        int hasPhoneNumber = Integer.parseInt(idCursor.getString(idCursor.getColumnIndex( HAS_PHONE_NUMBER )));
         Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
         if (hasPhoneNumber > 0) {
             Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

             while (phoneCursor.moveToNext()) {
                 phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                // output.append("\n Phone number:" + phoneNumber);
                 Toast.makeText(MainActivity.this, 
                          phoneNumber, Toast.LENGTH_LONG).show();
             }
         }


        Log.d(LOG_TAG, "search: "+id + " key: "+key + " name: "+name); 
    }
    idCursor.close();

但是当我在移动设备上运行该程序时,它显示错误"不幸的程序已关闭"

1 个答案:

答案 0 :(得分:0)

较短的版本;你仍然需要那个权限(android.permission.READ_CONTACTS)

public String getPhoneNumber(String name, Context context) {
String ret = null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        projection, selection, null, null);
if (c.moveToFirst()) {
    ret = c.getString(0);
}
c.close();
if(ret==null)
    ret = "Unsaved";
return ret;
}

希望它会对你有所帮助。