add Contact - Android Account

Android examples for Account:Contact

Description

add Contact

Demo Code


//package com.java2s;
import java.util.ArrayList;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;

import android.content.ContentValues;
import android.content.Context;

import android.provider.ContactsContract;

import android.provider.ContactsContract.RawContacts;

public class Main {

    public static void addContact(Context context, String name, String phone) {
        String[] ph = phone.trim().split(",");
        ContentResolver resolver = context.getContentResolver();
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
        ContentValues values = new ContentValues();
        values.put(RawContacts.AGGREGATION_MODE,
                RawContacts.AGGREGATION_MODE_DISABLED);
        ContentProviderOperation op1 = ContentProviderOperation
                .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValues(values).build();
        operations.add(op1);//  w ww  .ja v a 2s  .co m
        ContentProviderOperation op2 = ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(
                        ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(
                        ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(
                        ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                        name.trim()).build();
        operations.add(op2);
        for (int i = 0; i < ph.length; i++) {
            ContentProviderOperation op = ContentProviderOperation
                    .newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.NUMBER,
                            ph[i].trim())
                    .withValue(
                            ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM)
                    .build();
            operations.add(op);
        }
        try {
            resolver.applyBatch(ContactsContract.AUTHORITY, operations);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials