更新联系人姓名&以编程方式在android中编号

时间:2017-01-31 06:07:44

标签: android contacts android-contacts android-cursor

我创建了一个应用程序来读取,更新,删除联系人详细信息。这是更新联系人姓名和号码的问题。有人可以帮助我,我该怎么办呢。我使用以下代码,但它无法正常工作。

  @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

4 个答案:

答案 0 :(得分: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;
    }
}
希望这有效。

答案 1 :(得分:2)

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 :(得分:0)

我可能迟到了答案,但是这个对我有用。与其他答案的主要区别在于,我使用了ContactsContract.Data.CONTACT_ID而不是ContactsContract.Data.RAW_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);

答案 3 :(得分:0)

注意!

某些手机,例如三星edge系列手机号码中留有多余的空白。因此,例如,数字01234567将像012 23467这样保存。因此,请确保在使用Where子句查询时,该数字仍然有空格。

如果您手边有Raw联系人ID,则应该从该联系人获取所有电话号码,并在删除多余空格的同时检查电话号码。

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