update contact name & number in android programmatically

Secret picture Secret · Jan 31, 2017 · Viewed 7.4k times · Source

I create an Application to Read, Update, Delete Contacts Details. Here is a problem to updating Contact name and number.Could anyone help me please how can I do that. I am using the following code, but it's not working.

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_fragment_edit, container, false);

    textView = (TextView) view.findViewById(R.id.tvnew1);

    imageView = (ImageView) view.findViewById(R.id.newim1);
    save = (Button) view.findViewById(R.id.savebtn1);

    fName = (EditText) view.findViewById(R.id.firstname1);
    lName = (EditText) view.findViewById(R.id.lastname1);
    pNumber = (EditText) view.findViewById(R.id.pnumber1);

    String conName = getArguments().getString("name");
    String conNumber = getArguments().getString("number");
    int conId = getArguments().getInt("pos");

    Log.e("a", "name is : " + conName);
    Log.e("a", "number is : " + conNumber);
    Log.e("a", "id is :" + conId);

    fName.setText(conName);
    pNumber.setText(conNumber);

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, PICK_PHOTO);
        }
    });

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            UpdateContact(fName.getText().toString(),
                    pNumber.getText().toString(),
                    lName.getText().toString());
        }
    });

    return view;
}
public boolean UpdateContact(String name, String number, String Lastname) {
    boolean success = true;
    try {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
                                ContactsContract.Contacts.Data.MIMETYPE + "='" +
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
                        new String[]{name})
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
                .build());

        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
                                ContactsContract.Data.MIMETYPE + "='" +
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
                        new String[]{name})
                .withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, Lastname)
                .build());

        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
                                ContactsContract.Contacts.Data.MIMETYPE + "='" +
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
                        new String[]{name})
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
                .build());

        Log.e("a", "name is : " + name);
        Log.e("a", "number is : " + number);
        Log.e("a", "lastname is : " + Lastname);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        if (bitmap != null) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 75, stream);

            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
                                    ContactsContract.Data.MIMETYPE + "='" +
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
                            new String[]{name})
                    .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray())
                    .build());
            try {
                stream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            Toast.makeText(getActivity().getBaseContext(), "Contact is successfully Edit", Toast.LENGTH_SHORT).show();
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    fName.setText("");
    lName.setText("");
    pNumber.setText("");
    imageView.setImageResource(R.drawable.image);
    imageView.destroyDrawingCache();
    return success;
}

My Logcat is

   01-31 11:52:17.298 7212-7212/com.my.fragmentmy E/a: name is : Fh
   01-31 11:52:17.298 7212-7212/com.my.fragmentmy E/a: number is : 11 2554 4
   01-31 11:52:17.298 7212-7212/com.my.fragmentmy E/a: id is :0
   01-31 11:52:31.271 7212-7212/com.my.fragmentmy E/a: name is : Fhtyttyy
   01-31 11:52:31.271 7212-7212/com.my.fragmentmy E/a: number is : 11111111 2554 4
   01-31 11:52:31.271 7212-7212/com.my.fragmentmy E/a: lastname is : rrtttt
   01-31 11:52:31.271 7212-7212/com.my.fragmentmy E/a: phoneId id : phones

Answer

hsyn_tr picture hsyn_tr · Oct 9, 2018
private final static String[] DATA_COLS = {

    ContactsContract.Data.MIMETYPE,
    ContactsContract.Data.DATA1,//phone number
    ContactsContract.Data.CONTACT_ID
};


public static boolean updateNameAndNumber(final Context context, String number, String newName, String newNumber) {

        if (context == null || number == null || number.trim().isEmpty()) return false;

        if (newNumber != null && newNumber.trim().isEmpty()) newNumber = null;

        if (newNumber == null) return false;


        String contactId = getContactId(context, number);

        if (contactId == null) return false;

        //selection for name
        String where = String.format(
                "%s = '%s' AND %s = ?",
                DATA_COLS[0], //mimetype
                ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,
                DATA_COLS[2]/*contactId*/);

        String[] args = {contactId};

        ArrayList<ContentProviderOperation> operations = new ArrayList<>();

        operations.add(
                ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(where, args)
                        .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, newName)
                        .build()
        );

        //change selection for number
        where = String.format(
                "%s = '%s' AND %s = ?",
                DATA_COLS[0],//mimetype
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
                DATA_COLS[1]/*number*/);

        //change args for number
        args[0] = number;

        operations.add(
                ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(where, args)
                        .withValue(DATA_COLS[1]/*number*/, newNumber)
                        .build()
        );

        try {

            ContentProviderResult[] results = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations);

            for (ContentProviderResult result : results) {

                Log.d("Update Result", result.toString());
            }

            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    public static String getContactId(Context context, String number) {

        if (context == null) return null;

        Cursor cursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.CommonDataKinds.Phone.NUMBER + "=?",
                new String[]{number},
                null
        );

        if (cursor == null || cursor.getCount() == 0) return null;

        cursor.moveToFirst();

        String id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));

        cursor.close();
        return id;
    }