Save Contact to Context - Android Account

Android examples for Account:Contact

Description

Save Contact to Context

Demo Code


//package com.java2s;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class Main {

    public static void writeContact(Context context) {

        ContentResolver resolver = context.getContentResolver();

        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri = Uri.parse("content://com.android.contacts/data");
        ContentValues values = new ContentValues();

        Cursor cursor = resolver.query(uri, new String[] { "_id" }, null,
                null, null);//  w w w .j av  a  2 s.c o m
        cursor.moveToLast();
        int lastId = cursor.getInt(0);
        int newId = lastId + 1;
        values.put("contact_id", newId);
        resolver.insert(uri, values);

        ContentValues phoneValues = new ContentValues();
        phoneValues.put("data1", "123456789");
        phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");
        phoneValues.put("raw_contact_id", newId);
        resolver.insert(dataUri, phoneValues);

        ContentValues emailValues = new ContentValues();
        emailValues.put("data1", "xxm@163.com");
        emailValues.put("mimetype", "vnd.android.cursor.item/email_v2");
        emailValues.put("raw_contact_id", newId);
        resolver.insert(dataUri, emailValues);

        ContentValues nameValues = new ContentValues();
        nameValues.put("data1", "xxm");
        nameValues.put("mimetype", "vnd.android.cursor.item/name");
        nameValues.put("raw_contact_id", newId);
        resolver.insert(dataUri, nameValues);

    }
}

Related Tutorials