2014-03-30 67 views
0

如何通過其id/lookupkey檢索單個聯繫人和一些關聯數據(例如電子郵件,電話號碼,地址等)?如何檢索單個聯繫人

這是我用來添加聯繫人(實際上它來自互聯網,併爲我工作)的代碼。

// Asking the Contact provider to create a new contact 
    try { 
     result = this.context.getContentResolver().applyBatch(
       ContactsContract.AUTHORITY, ops); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     Toast.makeText(this.context, "Exception: " + e.getMessage(), 
       Toast.LENGTH_SHORT).show(); 
    } 

    Uri myContactUri = result[0].uri; 
    int lastSlash = myContactUri.toString().lastIndexOf("/"); 
    int length = myContactUri.toString().length(); 
    int contactID = Integer.parseInt((String) myContactUri.toString() 
      .subSequence(lastSlash + 1, length)); 

    return contactID; 

現在我想獲取這個新的聯繫人。我該怎麼做?所有我想出的是這樣的:

ContentResolver content = context.getContentResolver(); 

    String[] projection = { Data.LOOKUP_KEY, Data.MIMETYPE, 
      ContactsContract.Contacts._ID, 
      ContactsContract.Contacts.DISPLAY_NAME, 
      ContactsContract.CommonDataKinds.Phone.NUMBER, 
      ContactsContract.CommonDataKinds.Email.ADDRESS }; 

    // Defines the selection clause 
    String selection = Data.LOOKUP_KEY + " = ?"; 

    // Defines the sort order 
    String sortOrder = Data.LOOKUP_KEY; 

    String[] args = {"2400"}; 

    Cursor cursor = content.query(Data.CONTENT_URI, projection, selection, 
      args, sortOrder); 

當我刪除選擇我得到所有聯繫人+他們的所有數據。所以我查了一下我的案例中的關鍵2400,並希望通過它的lookupkey獲取這個聯繫人。那麼,不起作用。 cursor.getCount()返回0.

任何想法?

回答

0

我的解決方案現在是使用以下:

String[] projection = { Data.MIMETYPE, 
      ContactsContract.Contacts._ID, 
      ContactsContract.Contacts.DISPLAY_NAME, 
      ContactsContract.CommonDataKinds.Phone.NUMBER, 
      ContactsContract.CommonDataKinds.Email.ADDRESS }; 

    // Defines the selection clause 
    String selection = ContactsContract.Data.RAW_CONTACT_ID + "=?"; 

    // Defines the sort order 
    String sortOrder = Data.LOOKUP_KEY; 

    String[] args = { id+"" }; 

    Cursor cursor = content.query(Data.CONTENT_URI, projection, selection, 
      args, sortOrder); 

排序順序並不重要,但我用的是RAW_CONTACT_ID,效果很好!