2016-10-11 30 views
1

編程方式插入一個新的聯繫人的電話的時候,我試圖讓的ContactID新添加的聯繫人的編程。聯繫人正在成功添加並從獲取聯繫人ID ContentProviderResult []contactId我得到的不是正確的。我也看到thisthis答案,但的ContactID不正確的。這裏是我的代碼獲取的ContactID在安卓

ArrayList<ContentProviderOperation> contentProviderOperation = new ArrayList<>(); 
     ...... 
     ...... 

ContentProviderResult[] results = getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation); 
long contactId = ContentUris.parseId(results[0].uri); 

我也曾嘗試下面的代碼:

ContentProviderResult[] results = getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation); 
      Uri myContactUri = results[0].uri; 

      int lastSlash = myContactUri.toString().lastIndexOf("/"); 
      int length = myContactUri.toString().length(); 
      int contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash+1, length)); 

的ContactID我到這兒是不是正確的。如果我出錯了,請糾正我。提前致謝。

回答

2

定期參加工作後我找到一種方法通過下面的代碼,找出正確的的ContactID

public static int getContactIDFromNumber(String contactNumber, Context context) { 
     contactNumber = Uri.encode(contactNumber); 
     int phoneContactID = new Random().nextInt(); 
     Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, contactNumber), new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null); 
     while (contactLookupCursor.moveToNext()) { 
      phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID)); 
     } 
     contactLookupCursor.close(); 

     return phoneContactID; 
    } 

傳遞新添加的聯繫人的的ContactID中存在的ArrayList。 我知道這不是找到聯繫人的正確方法。但它適用於我。