簡體   English   中英

從名稱獲取android中的聯系電話

[英]Get Contact Number in android from name

我是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();

但是,當我在移動設備上運行程序時,它顯示錯誤“不幸的是,程序已關閉”

較短的版本; 您仍然需要該權限(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;
}

希望對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM