2012-12-19 68 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

相關問題