add Contact to Context - Android Account

Android examples for Account:Contact

Description

add Contact to Context

Demo Code


//package com.java2s;
import android.content.ContentValues;
import android.content.Context;

import android.net.Uri;
import android.provider.ContactsContract;

public class Main {

    public static int addContact(Context context, String name, String number) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("display_name", name);

        Uri uri = context.getContentResolver().insert(
                ContactsContract.RawContacts.CONTENT_URI, contentValues);

        if (!uri.getLastPathSegment().matches("^\\d+$"))
            return 0;
        int id = Integer.parseInt(uri.getLastPathSegment());
        if (id == 0)
            return 0;

        contentValues.clear();//from   w  w w  .  j  a va2 s  .com

        contentValues.put("raw_contact_id", id);
        contentValues.put("mimetype", "vnd.android.cursor.item/phone_v2");
        contentValues.put("data1", number);
        context.getContentResolver().insert(
                ContactsContract.Data.CONTENT_URI, contentValues);

        contentValues.clear();
        contentValues.put("raw_contact_id", id);
        contentValues.put("mimetype", "vnd.android.cursor.item/name");
        contentValues.put("data1", name);
        context.getContentResolver().insert(
                ContactsContract.Data.CONTENT_URI, contentValues);
        return id;
    }
}

Related Tutorials