简体   繁体   中英

android Editing contact programmatically

I'm trying to edit contact details programmatically. I want to change the contact name having the phone number is equal to 123. Here is my Non working code.

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

        // This query will return NAME and ID of contact, 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();
        }

Currently I'm finding the phone number and getting the phone number's ID. With ID I'm trying to update it, seems it's not updating the phone number with ID.

here is working code for me.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM