简体   繁体   中英

Update android contact's email programmatically

Lets say I have a contact with only phone number and name.

Now I want to update contact and ADD E-mail information.

what I do -

 public void updateMail(String name, String mail) {
        ContentResolver cr = mcontext.getContentResolver();
        String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
               ContactsContract.Data.MIMETYPE + " = ? AND " +
               String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";

        String[] params = new String[] {name,
                 ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
                 String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)};

        Cursor phoneCur =   
               mcontext.getContentResolver().query(ContactsContract.Data.CONTENT_URI,   
               null, where, params, null);
        ArrayList<ContentProviderOperation> ops = new  
               ArrayList<ContentProviderOperation>();

        if ( (null == phoneCur)  ) {
        //createContact(name, phone);
            Log.e(TAG, "null == phoneCur");

         } else {

         ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                     .withSelection(where, params)
                     .withValue(ContactsContract.CommonDataKinds.Email.DATA, mail)
                     .build());
       }

         phoneCur.close();

         try {
            cr.applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (RemoteException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    }

It works only if I ALREADY HAVE contact with e-mail field. If I don't have it - nothing happens. How can I solve this problem?

if ((null == phoneCur)) , In this code you have checked if Contact information is present or not. If it is null (No contact) then you have missed the ops.add() code.

You either remove this condition if ((null == phoneCur)) or add 'ops.add()' in the 'if' block.

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