Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update contact name & number in android programmatically

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
like image 804
Secret Avatar asked Mar 11 '23 00:03

Secret


2 Answers

try this,

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;


public class Contacts {


    public static boolean addContactList(Context context,int id, String contactName, String contactNumber){


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

        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
        builder.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null);
        builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
        ops.add(builder.build());

        // Name
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactName);
        ops.add(builder.build());

        // Number
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactNumber);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
        ops.add(builder.build());
        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            return true;

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

    }

    public static HashMap<String,String> getContactList(Context context){

        HashMap<String,String> contact = new HashMap<>();

        Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                new String[] {ContactsContract.Data._ID,
                        ContactsContract.CommonDataKinds.Phone.NUMBER,
                        ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.LABEL}, null, null, null);

        if(null != c){
            String data = "";
            while(c.moveToNext()){
                if(c.getString(3) != null){
                    data = c.getString(0)+" "+c.getString(1)+" "+c.getString(2)+" "+c.getString(3)+"\n";
                    //position 0 - id
                    //position 1 - contact
                    //position 2 - type
                    //position 3 - label/name
                    contact.put(c.getString(3),c.getString(1));
                }
            }
            c.close();
        }
        return  contact;
    }


    public static boolean updateContactList(Context context,String name,String newPhoneNumber){
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
                ContactsContract.Data.MIMETYPE + " = ? AND " +
                String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";

        String[] params = new String[] {name,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
                String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(where, params)
                .withValue(ContactsContract.CommonDataKinds.Phone.DATA, newPhoneNumber)
                .build());
        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            return true;

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

        public static boolean deleteContactList(Context context,String name){
            ContentResolver cr = context.getContentResolver();
            String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
            String[] params = new String[] {name};

            ArrayList<ContentProviderOperation> ops = new ArrayList<>();
            ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
                    .withSelection(where, params)
                    .build());
            try {
                cr.applyBatch(ContactsContract.AUTHORITY, ops);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

    public static boolean contactExists(Context context, String name) {
        Uri lookupUri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(name));
        String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.DISPLAY_NAME };
        Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
        try {
            if (cur.moveToFirst()) {
                return true;
            }
        } finally {
            if (cur != null)
                cur.close();
        }
        return false;
    }
}

hope this works.

like image 41
chetan Avatar answered Mar 15 '23 01:03

chetan


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;
    }
like image 65
hsyn_tr Avatar answered Mar 15 '23 00:03

hsyn_tr