2012-12-19 32 views
4

我使用下面的代码从android联系人中检索姓和名.DISPLAY_NAME在姓和名返回1时返回联系人的姓名,下面是代码。从android联系人中检索名字和姓氏导致'1'和'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._ID)); 
      String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
      if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
       Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id }, null); 
       while (pCur.moveToNext()) { 
        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
        String firstname = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)); 
        String lastname = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)); 
        System.out.println("firstname and lastname" + firstname+ " "+lastname); 
        phoneNo = phoneNo.replaceAll("\\D", ""); 
        names.add(name); 
        phnno.add(phoneNo); 
       } 
       pCur.close(); 
      } 
     }   
    } 

当我改变行cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI到cr.query(ContactsContract.Data.CONTENT_URI我得到的日志作为

enter image description here

建议高度提前appreciated.Thanks

+0

这可能是链接联系人,也许没有附加名称? – breadbin

+0

我亲自添加了他们,就在我编写代码之前。他们都附上了姓名 –

+0

您是否找到解决方案?我遇到同样的问题 –

回答

9

下面的代码会帮助你的姓氏和名字:

Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId); 
Uri dataUri = Uri.withAppendedPath(contactUri, Contacts.Data.CONTENT_DIRECTORY); 
Cursor nameCursor = getActivity().getContentResolver().query(
     dataUri, 
     null, 
     Data.MIMETYPE+"=?", 
     new String[]{ StructuredName.CONTENT_ITEM_TYPE }, 
     null); 
      while (nameCursor.moveToNext()) 
      { 

       String  firstName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA2)); 
       String lastName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA3)); 

       Toast.makeText(getApplicationContext(), "First name"+firstName, Toast.LENGTH_LONG).show(); 
       Toast.makeText(getApplicationContext(), "Second name"+lastName, Toast.LENGTH_LONG).show(); 

       return new String [] {firstName , lastName}; 
      } 

      nameCursor.close(); 
+0

谢谢,经过大量的搜索,这是唯一的解决方案,为我工作。常量名称如“DATA1”和“DATA2”,而不是更直观或有意义的东西太糟糕了。 – CACuzcatlan

+4

你应该使用这个而不是DATA1,DATA2等。http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.StructuredName.html –

+0

Joyson,谢谢。这真的很有帮助。只有这个代码适合我 – Konstantin

相关问题