如何在Android中检索联系人姓名和电话号码

前端之家收集整理的这篇文章主要介绍了如何在Android中检索联系人姓名和电话号码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 Android开发的新手,我正在尝试用名称和电话号码检索联系人列表.我尝试以下代码
// Get a cursor over every contact.
    Cursor cursor = getContentResolver().query(People.CONTENT_URI,null,null); 
    // Let the activity manage the cursor lifecycle.
    startManagingCursor(cursor);
    // Use the convenience properties to get the index of the columns
    int nameIdx = cursor.getColumnIndexOrThrow(People.NAME); 

    int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
    String[] result = new String[cursor.getCount()];
    if (cursor.moveToFirst())
      do { 
        // Extract the name.
        String name = cursor.getString(nameIdx);
        // Extract the phone number.
        String phone = cursor.getString(phoneIdx);
        result[cursor.getPosition()] = name + "-" +" "+  phone;
      } while(cursor.moveToNext());

代码应该返回一个数组,其中包含所有联系人姓名及其电话号码,但这只能返回联系人的姓名,并在电话号码中返回NULL,

示例输出

John - null

请在这方面帮助我这个代码中有什么问题.
在此方面的任何帮助都将非常感谢,并提前紧急感谢.

解决方法

在Android清单中:
<uses-permission android:name="android.permission.READ_CONTACTS" />

然后在活动中:

editText.setOnFocusChangeListener(new OnFocusChangeListener(){

            @Override
            public void onFocusChange(View v,boolean hasFocus) {
                if(hasFocus){
                    editText.setText("");   
                     Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
                     startActivityForResult(intent,PICK_CONTACT);
                }
            }           
        });

然后你必须抓住动作选择联系人的结果:

@Override 
public void onActivityResult(int reqCode,int resultCode,Intent data){ 
    super.onActivityResult(reqCode,resultCode,data);

    switch(reqCode)
    {
       case (PICK_CONTACT):
         if (resultCode == Activity.RESULT_OK)
         {
             Uri contactData = data.getData();
             Cursor c = managedQuery(contactData,null);
              if (c.moveToFirst())
              {
                  String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                  String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                  if (hasPhone.equalsIgnoreCase("1")) 
                  {
                      Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null);
                      phones.moveToFirst();
                      String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                       Toast.makeText(getApplicationContext(),cNumber,Toast.LENGTH_SHORT).show();

                      String nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

                      editText.setText(nameContact+ " "+ cNumber);
                  }
             }
       }
    }
}

猜你在找的Android相关文章