79 本帖最后由 YooHi 于 2013-7-1 19:26 編輯 新手一枚,剛學(xué)到此處,綜合前人經(jīng)驗(yàn),搞定此處理,方便后來(lái)者,錯(cuò)誤及待優(yōu)化之處往高手指點(diǎn),感謝!
---------------------------------------------------MainActivity------------------------------------------------------------------------------------------------------
package com.eboy.readwritecontact;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import com.eboy.test.*;
public class MainActivity extends Activity {
String strName = "";
String strPhone = "";
String strAllContacts = "";
final String tag ="MainThread";
ContactsOptions ct = new ContactsOptions();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//添加用戶信息
//String name, String phone, String email, String address, String nickname,
//String organization, String website, String QQ
ct.AddOneContact(this, "張三", "33333333333", "88888888@139.com", "江蘇省徐州市,221600",
"zhangsan", "中國(guó)石化", "http://www.yoohi.com.cn", "12345678");
//依據(jù)號(hào)碼查詢姓名/郵箱/。。。。。。,多個(gè)返回之間用下劃線"_"分割
//(Context,number,name,mimetype)
strName = ct.QueryContacts(this, "13916061000", "", "vnd.android.cursor.item/email_v2");
//String str[] = strName.split("_");//int i = str.length;
//依據(jù)姓名查詢號(hào)碼/郵箱/。。。。。。。。,多個(gè)返回之間用下劃線"_"分割
strPhone = ct.QueryContacts(this, "","First", "vnd.android.cursor.item/email_v2");
Log.i(tag, "strName:" + strName + " strPhone:" + strPhone);
//String str1[] = strPhone.split("_");//int i = str1.length;
//查詢所有用戶列表及對(duì)應(yīng)信息
strAllContacts = ct.ReadAllContacts(this);
Log.i(tag, strAllContacts);
//String name, String phone, String email, String address, String nickname,
//String organization, String website, String QQ
//name_phone_email_address_nickname_organization_website_qq_
String contact[] = {"first_13011111111_hello@china.com__nickname_easyfly_www.yoohi.cn_87654321_",
"second_13022222222_hello@china.com__nickname_easyfly_www.yoohi.cn_87654321_",
"third_13033333333_thanks@china.com_江蘇徐州_peter_yoohi_www.yoohi.com.cn_12345678_",
"four_13044444444_zhejiang@china.com_中國(guó)上海_michael_easyfly_www.yoohi.taobao.com_88884444_"};
ct.AddContactsInTransaction(this,contact);
//update contact
ct.UpdateContact(this, "second", "88888888888");
//(Context,name1_name2_name3_)
ct.DeleteContact(this, "first_second_third_four_");
} catch (Exception e) {
e.printStackTrace();
Log.i(tag, "---------------------------------------");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
------------------------------------------ContactsOptions ---------------------------------------------------------------------------------------------------------------
package com.eboy.test;
import java.util.ArrayList;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.Data;
import android.test.AndroidTestCase;
import android.util.Log;
/*
1.先讀取contacts表,獲取ContactsID;
2.再在raw_contacts表中根據(jù)ContactsID獲取RawContactsID;
3.然后就可以在data表中根據(jù)RawContactsID獲取該聯(lián)系人的各數(shù)據(jù)了;
*/
public class ContactsOptions extends AndroidTestCase {
private String strQuery = "";
private String strReadAll = "";
private static final String tag = "TestContact";
// 查詢指定電話的聯(lián)系人姓名,郵箱,
public String QueryContacts(Context context, String number, String name,
String mimetype) throws Exception {
if (context == null || (name.length() == 0 && number.length() == 0))
return strQuery;
String str = "";
strQuery = "";
Uri uri = Uri
.parse("content://com.android.contacts/data/phones/filter/"
+ number);
ContentResolver resolver = context.getContentResolver();
// 按照號(hào)碼查詢名字
if (number.length() > 0) {
Cursor cursor = resolver.query(uri,
new String[] { Data.DISPLAY_NAME }, null, null, null);
if (cursor.moveToFirst()) {
strQuery = cursor.getString(0);
name = strQuery;
// 表示通過(guò)號(hào)碼查詢其他內(nèi)容
if (mimetype.length() > 0) {
strQuery = "";
}
// Log.i(tag, strQuery);
}
cursor.close();
}
// 按照名字查詢號(hào)碼
if (name.length() > 0) {
uri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = resolver.query(uri, new String[] { Data.DATA1,
Data.MIMETYPE }, "display_name=?", new String[] { name },
null);
if (cursor.moveToFirst()) {
do {// 遍歷所有的電話號(hào)碼
// str = cursor.getString(0);
// Log.i("遍歷:", str+"/");
if (cursor.getString(cursor.getColumnIndex("mimetype"))
.equals(mimetype)) {
str = "";
str = cursor.getString(0);
strQuery += str.replace("-", "") + "_";
}
} while (cursor.moveToNext());
}
cursor.close();
return strQuery;// phone
}
return strQuery;
}
// 讀取通訊錄的全部的聯(lián)系人
// 需要先在raw_contact表中遍歷id,并根據(jù)id到data表中獲取數(shù)據(jù)
public String ReadAllContacts(Context context) {
Uri uri = Uri.parse("content://com.android.contacts/contacts"); // 訪問raw_contacts表
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(uri, new String[] { Data._ID }, null,
null, null); // 獲得_id屬性
while (cursor.moveToNext()) {
StringBuilder buf = new StringBuilder();
int id = cursor.getInt(0);// 獲得id并且在data中尋找數(shù)據(jù)
buf.append("id=" + id);
uri = Uri.parse("content://com.android.contacts/contacts/" + id
+ "/data"); // 如果要獲得data表中某個(gè)id對(duì)應(yīng)的數(shù)據(jù),則URI為content://com.android.contacts/contacts/#/data
Cursor cursor2 = resolver.query(uri, new String[] { Data.DATA1,
Data.MIMETYPE }, null, null, null); // data1存儲(chǔ)各個(gè)記錄的總數(shù)據(jù),mimetype存放記錄的類型,如電話、email等
while (cursor2.moveToNext()) {
String data = cursor2
.getString(cursor2.getColumnIndex("data1"));
if (cursor2.getString(cursor2.getColumnIndex("mimetype"))
.equals("vnd.android.cursor.item/name")) { // 如果是名字
buf.append(",name=" + data);
} else if (cursor2
.getString(cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/phone_v2")) { // 如果是電話
data = data.replace("-", "");
buf.append(",phone=" + data);
} else if (cursor2
.getString(cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/email_v2")) { // 如果是email
buf.append(",email=" + data);
} else if (cursor2
.getString(cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/nickname")) { // 如果是昵稱
buf.append(",nickname=" + data);
} else if (cursor2
.getString(cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/postal-address_v2")) { // 如果是地址
buf.append(",address=" + data);
} else if (cursor2
.getString(cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/organization")) { // 如果是組織
buf.append(",organization=" + data);
} else if (cursor2
.getString(cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/website")) { // 如果是website
buf.append(",website=" + data);
} else if (cursor2
.getString(cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/note")) { // 如果是note
buf.append(",note=" + data);
}
}
String str = buf.toString();
strReadAll += "
" + str;
}
return strReadAll;
}
// 單條添加
public void AddOneContact(Context context, String name, String phone,
String email, String address, String nickname, String organization,
String website, String QQ) {
// 插入raw_contacts表,并獲取_id屬性
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
ContentResolver resolver = context.getContentResolver();
ContentValues values = new ContentValues();
long contact_id = ContentUris.parseId(resolver.insert(uri, values));
// 插入data表
uri = Uri.parse("content://com.android.contacts/data");
// add Name
if (name.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE, "vnd.android.cursor.item/name");
// values.put("data2", "zs001");
values.put("data1", name);
resolver.insert(uri, values);
values.clear();
}
// add Phone
if (phone.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE, "vnd.android.cursor.item/phone_v2");
// values.put("data2", "2"); // 手機(jī)
values.put("data1", phone);
resolver.insert(uri, values);
values.clear();
}
// add email
if (email.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE, "vnd.android.cursor.item/email_v2");
// values.put("data2", "2");
values.put("data1", email);
resolver.insert(uri, values);
values.clear();
}
// add address
if (address.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE,
"vnd.android.cursor.item/postal-address_v2");
// values.put("data2", "2");
values.put("data1", address);
resolver.insert(uri, values);
values.clear();
}
// add nickname
if (nickname.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE, "vnd.android.cursor.item/nickname");
// values.put("data2", "2");
values.put("data1", nickname);
resolver.insert(uri, values);
values.clear();
}
// add organization
if (organization.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE, "vnd.android.cursor.item/organization");
// values.put("data2", "2");
values.put("data1", organization);
resolver.insert(uri, values);
values.clear();
}
// add website
if (website.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE, "vnd.android.cursor.item/website");
// values.put("data2", "2");
values.put("data1", website);
resolver.insert(uri, values);
values.clear();
}
// add QQ
if (QQ.length() > 0) {
values.put("raw_contact_id", contact_id);
values.put(Data.MIMETYPE, "vnd.android.cursor.item/note");
// values.put("data2", "2"); // 單位
values.put("data1", QQ);
resolver.insert(uri, values);
values.clear();
}
}
// 批量添加
public void AddContactsInTransaction(Context context, String contacts[])
throws Exception {
Uri uri;
ContentResolver resolver = context.getContentResolver();
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
String str[] = null;
for (int i = 0; i < contacts.length; i++) {
str = contacts.split("_");
uri = Uri.parse("content://com.android.contacts/raw_contacts");
// 向raw_contact表添加一條記錄
// 此處.withValue("account_name", null)一定要加,不然會(huì)拋NullPointerException
ContentProviderOperation operation1 = ContentProviderOperation
.newInsert(uri).withValue("account_name", null).build();
operations.add(operation1);
// 向data添加數(shù)據(jù)
uri = Uri.parse("content://com.android.contacts/data");
// 添加姓名
ContentProviderOperation operation2 = ContentProviderOperation
.newInsert(uri)
.withValueBackReference("raw_contact_id", 3 * i)
// withValueBackReference的第二個(gè)參數(shù)表示引用operations[0]的操作的返回id作為此值
.withValue("mimetype", "vnd.android.cursor.item/name")
.withValue("data1", str[0]).build();
operations.add(operation2);
// 添加手機(jī)數(shù)據(jù)
ContentProviderOperation operation3 = ContentProviderOperation
.newInsert(uri)
.withValueBackReference("raw_contact_id", 3 * i)
.withValue("mimetype", "vnd.android.cursor.item/phone_v2")
.withValue("data2", "1").withValue("data1", str[1]).build();// data2部分?jǐn)?shù)據(jù)代表home,mobile,work等等屬性
operations.add(operation3);
}
resolver.applyBatch("com.android.contacts", operations);
}
// 刪除某人通訊錄,name格式name1_name2_name3_.......以_結(jié)束
public void DeleteContact(Context context, String name) throws Exception {
Uri uri;
String str[] = name.split("_");// 姓名list
for (int i = 0; i < str.length; i++) {
// 根據(jù)姓名求id
uri = Uri.parse("content://com.android.contacts/raw_contacts");
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(uri, new String[] { Data._ID },
"display_name=?", new String[] { str }, null);
if (cursor.moveToFirst()) {
int id = cursor.getInt(0);
Log.i(tag, "delete id:" + id);
// 根據(jù)id刪除data中的相應(yīng)數(shù)據(jù)
resolver.delete(uri, "display_name=?", new String[] { str });// 從raw_contacts表中刪除
uri = Uri.parse("content://com.android.contacts/data");
resolver.delete(uri, "raw_contact_id=?",
new String[] { id + "" });// 從data表中刪除
}
}
}
// 更新電話號(hào)碼
public void UpdateContact(Context context, String name, String phone)
throws Exception {
//int id = 0;
//Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
ContentResolver resolver = context.getContentResolver();
//Cursor cursor = resolver.query(uri, new String[] { Data._ID },
// "display_name=?", new String[] { name }, null);
Uri uri = Uri.parse("content://com.android.contacts/data");// 對(duì)data表的所有數(shù)據(jù)操作
ContentValues values = new ContentValues();
values.put("data2", "2");
values.put("data1", phone);
/*
if (cursor.moveToFirst()) {
id = cursor.getInt(0);
Log.i(tag, "update id:" + id);
}
*/
//resolver.update(uri, values, "mimetype=? and raw_contact_id=?",
// new String[] { "vnd.android.cursor.item/phone_v2", id + "" });
resolver.update(uri, values, "mimetype=? and display_name=?",
new String[] { "vnd.android.cursor.item/phone_v2", name });
}
public static void main(String[] args) {
}
}
</i |