2016-08-19 129 views
1

我試圖編輯編輯聯繫人詳細信息。我想更改電話號碼等於123的聯繫人姓名。以下是我的非工作代碼。android編程式編輯聯繫人

Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode("123")); 

     // This query will return NAME and ID of conatct, associated with phone //number. 

     Cursor mcursor = getContentResolver().query(lookupUri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null); 

     //Now retrive _ID from query result 
     long idPhone = 0; 
     try { 
      if (mcursor != null) { 
       if (mcursor.moveToFirst()) { 
        idPhone = Long.valueOf(mcursor.getString(mcursor.getColumnIndex(ContactsContract.PhoneLookup._ID))); 
        String getID = String.valueOf(idPhone); 
        Toast.makeText(this.getApplicationContext(), getID, Toast.LENGTH_LONG).show(); 
        Uri uri= ContentUris.withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,3625); 
        ContentValues values = new ContentValues(); 
        values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,"After Changed name"); 
        getContentResolver().update(uri, values, ContactsContract.CommonDataKinds.Phone._ID+"=?", new String[] {String.valueOf(idPhone)}); 

       } 
      } 
     } finally { 
      mcursor.close(); 
     } 

目前我正在查找電話號碼並獲取電話號碼的ID。有了ID我試圖更新它,似乎它不更新帶有ID的電話號碼。

任何幫助將不勝感激!

回答

0

這裏是我的工作代碼。

public void updateContact (String contactId, String newNumber, Activity act) throws RemoteException, OperationApplicationException{ 

    //ASSERT: @contactId alreay has a work phone number 
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 
    String selectPhone = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" + 
        Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Phone.TYPE + "=?"; 
    String[] phoneArgs = new String[]{contactId, String.valueOf(Phone.TYPE_WORK)}; 
    ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI) 
      .withSelection(selectPhone, phoneArgs) 
      .withValue(Phone.NUMBER, newNumber) 
      .build()); 
    act.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 
} 


//hope this also work for you. 
+0

我已經有電話號碼。我想從給定的電話號碼更改聯繫人姓名。 –

+0

通過聯繫人號碼作爲contactId中的參數 – Vij

+0

這不起作用。請更新您的代碼。 –