利用内容提供者来操作联系人数据库
添加权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
package cn.itcast.contacts.test;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
public class TestContacts extends AndroidTestCase {
public void readContacts() throws Exception{
//1. 查看源代码
// com.android.contacts/raw_contacts
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Cursor cursor = getContext().getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString( cursor.getColumnIndex("_id"));
String name = cursor.getString( cursor.getColumnIndex("display_name"));
//System.out.println(id);
System.out.println("姓名"+ name);
//System.out.println("--");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
Cursor datacursor = getContext().getContentResolver().query(dataUri, null, "raw_contact_id=?", new String[]{id}, null);
while (datacursor.moveToNext()) {
/* System.out.println( datacursor.getString(datacursor.getColumnIndex("data1")));
System.out.println( datacursor.getString( datacursor.getColumnIndex("mimetype")));
System.out.println("~~~~~~~~~~~~~");*/
if("vnd.android.cursor.item/phone_v2".equals(datacursor.getString( datacursor.getColumnIndex("mimetype")))){
System.out.println("电话"+datacursor.getString(datacursor.getColumnIndex("data1")));
}else if("vnd.android.cursor.item/email_v2".equals(datacursor.getString( datacursor.getColumnIndex("mimetype")))){
System.out.println("邮箱"+datacursor.getString(datacursor.getColumnIndex("data1")));
}
}datacursor.close();
}
cursor.close();
}
public void insertContacts(){
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
ContentValues values = new ContentValues();
values.put("display_name", "zhaoba");
Uri inserturi = getContext().getContentResolver().insert(uri, values);
//得到插入的数据 在数据库中的_id
long id = ContentUris.parseId(inserturi);
Uri dataUri = Uri.parse("content://com.android.contacts/data");
ContentValues phonevalues = new ContentValues();
phonevalues.put("data1", "7777");
phonevalues.put("raw_contact_id", id);
phonevalues.put("mimetype", "vnd.android.cursor.item/phone_v2");
getContext().getContentResolver().insert(dataUri, phonevalues);
ContentValues emailvalues = new ContentValues();
emailvalues.put("data1", 77777@qq.com);
emailvalues.put("raw_contact_id", id);
emailvalues.put("mimetype", "vnd.android.cursor.item/email_v2");
getContext().getContentResolver().insert(dataUri, emailvalues);
ContentValues namevValues = new ContentValues();
namevValues.put("mimetype", "vnd.android.cursor.item/name");
namevValues.put("raw_contact_id", id);
namevValues.put("data1", "yunchao");
getContext().getContentResolver().insert(dataUri, namevValues);
}
}
转载于:https://blog.51cto.com/asalinux/903509