2011-04-01 96 views
4

在我的應用程序中,我需要從電話地址簿中刪除特定的聯繫人,但我只是刪除了特定的號碼而不是全部聯繫人,所以請在此幫助我。在android中刪除特定聯繫人

在此先感謝。

回答

7

要刪除所有聯繫人,請使用以下代碼;

ContentResolver cr = getContentResolver(); 
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, 
     null, null, null, null); 
    while (cur.moveToNext()) { 
     try{ 
      String lookupKey = cur.getString(cur.getColumnIndex(
       ContactsContract.Contacts.LOOKUP_KEY)); 
      Uri uri = Uri.withAppendedPath(ContactsContract. 
       Contacts.CONTENT_LOOKUP_URI, lookupKey); 
      System.out.println("The uri is " + uri.toString()); 
      cr.delete(uri, null, null); 
     } 
    catch(Exception e) 
    { 
     System.out.println(e.getStackTrace()); 
    } 
} 

刪除任何特定的聯繫人修改查詢

cr.delete(uri, null, null); 

希望它可以幫助!

1

也可以嘗試這個代碼

private void deletePhoneNumber(Uri peopleUri, String numberToDelete) { 

    Uri.Builder builder = peopleUri.buildUpon(); 
    builder.appendEncodedPath(People.Phones.CONTENT_DIRECTORY); 
    Uri phoneNumbersUri = builder.build(); 


    String[] mPhoneNumberProjection = { People.Phones._ID, People.Phones.NUMBER }; 
    Cursor cur = resolver.query(phoneNumbersUri, mPhoneNumberProjection, 
        null, null, null); 

    ArrayList<String> idsToDelete = new ArrayList<String>(); 

    if (cur.moveToFirst()) { 
      final int colId = cur.getColumnIndex(People.Phones._ID); 
      final int colNumber = cur.getColumnIndex(People.Phones.NUMBER); 

      do { 
        String id = cur.getString(colId); 
        String number = cur.getString(colNumber); 
        if(number.equals(numberToDelete)) 
          idsToDelete.add(id); 
      } while (cur.moveToNext()); 
    } 
    cur.close(); 

    for (String id : idsToDelete) { 
      builder.encodedPath(People.Phones.CONTENT_DIRECTORY + "/" + id); 
      phoneNumbersUri = builder.build(); 
      resolver.delete(phoneNumbersUri, "1 = 1", null); 
    } 
} 

希望它可以幫助!