以编程方式更新android中的联系人姓名和号码

Posted

技术标签:

【中文标题】以编程方式更新android中的联系人姓名和号码【英文标题】:update contact name & number in android programmatically 【发布时间】:2017-06-16 11:39:47 【问题描述】:

我创建了一个应用程序来读取、更新、删除联系人详细信息。这是更新联系人姓名和号码的问题。谁能帮助我,请问我该怎么做。我正在使用以下代码,但它不起作用。

  @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;

我的 Logcat 是

   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

【问题讨论】:

看到这个..***.com/questions/16887240/… 在 logcat 中显示名称和号码已更改,但联系人未在设备中编辑 【参考方案1】:
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;
    

【讨论】:

【参考方案2】:

试试这个,

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;
    

希望这行得通。

【讨论】:

是,但在 logcat 中显示名称和号码已更改,但联系人未在设备中编辑【参考方案3】:

我可能会迟到答案,但这对我有用。与其他答案的主要区别在于,我使用的是ContactsContract.Data.RAW_CONTACT_ID,而不是ContactsContract.Data.CONTACT_ID。当您获取 raw_id - rawContactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)); 的联系人对象查询时

ContentResolver contentResolver = activity.getContentResolver();

            String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND "
                    + ContactsContract.Data.MIMETYPE + " = ?";

            String[] nameParams = new String[]rawContactId,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE;
            String[] numberParams = new String[]rawContactId,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;

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

            if (!name.isEmpty()) 
                ops.add(android.content.ContentProviderOperation.newUpdate(
                        android.provider.ContactsContract.Data.CONTENT_URI)
                        .withSelection(where, nameParams)
                        .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                name).build());
            
            if (!number.isEmpty()) 
                ops.add(android.content.ContentProviderOperation.newUpdate(
                        android.provider.ContactsContract.Data.CONTENT_URI)
                        .withSelection(where, numberParams)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
                        .build());
            
            contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);

【讨论】:

【参考方案4】:

小心!

某些手机,例如 samsung edge 系列在手机号码中添加了额外的空白。因此,例如号码 01234567 将像 012 23467 一样保存。因此,当您使用 Where 子句查询时,请确保该数字仍然有空格。

如果您手头有原始联系人 ID,那么您应该从该联系人获取所有号码并检查号码,同时删除多余的空格。

number = number.replaceAll("[\\s|\\u00A0]+", ""); would remove extra space

【讨论】:

以上是关于以编程方式更新android中的联系人姓名和号码的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式编辑联系人的姓名/电话号码

在 iOS 中以编程方式呼叫号码时显示联系人姓名

android以编程方式编辑联系人

如何在android中以编程方式将铃声添加到本机应用程序联系人

如何删除以编程方式添加新联系人时添加的 Android 联系人应用程序中的重复条目?

Android通过电话号码有效地获取联系人姓名以在ListView中显示