2016-02-14 43 views
0

我的代碼返回ID = 1367(正確的ID是233)。哪裏不對?我有工作代碼通過電話號碼搜索ID,但我需要將其更改爲按顯示名稱進行搜索。通過顯示名稱找到聯繫人ID返回錯誤ID

String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + mStructuredName +"%'"; 
         String[] projection = new String[] { ContactsContract.PhoneLookup._ID}; 
         Cursor mcursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
           projection, selection, null, null); 

         long idPhone = 0; 
         try { 
          if (mcursor != null) { 
           if (mcursor.moveToFirst()) { 
            idPhone = Long.valueOf(mcursor.getString(0)); 
           } 
          } 
         } finally { 
          if (mcursor != null) { 
           mcursor.close(); 
          } 
         } 
         if (idPhone > 0) { 
          Intent intent = new Intent(Intent.ACTION_EDIT); 
          intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idPhone)); 
          startActivity(intent); 
         } 

按電話號碼(工作)

Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(tempPhoneNum)); 
       Cursor mcursor = getContentResolver().query(lookupUri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null); 
       long idPhone = 0; 
       try { 
        if (mcursor != null) { 
         if (mcursor.moveToFirst()) { 
          idPhone = Long.valueOf(mcursor.getString(mcursor.getColumnIndex(ContactsContract.PhoneLookup._ID))); 
         } 
        } 
       } finally { 
        if (mcursor != null) { 
         mcursor.close(); 
        } 
       } 

       if (idPhone > 0) { 
        Intent intent = new Intent(Intent.ACTION_EDIT); 
        intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idPhone)); 
        startActivity(intent); 
       } 

回答

0

你的代碼看起來太複雜了,在這裏搜索是我:

Cursor contacts_cur = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +" = ?", 
      new String[]{name}, null); 

contacts_cur.moveToNext(); 

String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 

需要注意的是,似乎危險爲我找回由於兩個聯繫人可以具有相同的名稱(但不是相同的ID),因此可以使用id來命名。