1.查找、增加、删除、修改联系人
直接贴代码:
ContactsManager.java
- package com.example.siqi.contacts;
- import java.util.ArrayList;
- import android.content.ContentProviderOperation;
- import android.content.ContentResolver;
- import android.database.Cursor;
- import android.provider.ContactsContract;
- import android.util.Log;
- public class ContactsManager {
- private ContentResolver contentResolver;
- private static final String TAG = "ContactsManager";
- /**
- * Use a simple string represents the long.
- */
- private static final String COLUMN_CONTACT_ID =
- ContactsContract.Data.CONTACT_ID;
- private static final String COLUMN_RAW_CONTACT_ID =
- ContactsContract.Data.RAW_CONTACT_ID;
- private static final String COLUMN_MIMETYPE =
- ContactsContract.Data.MIMETYPE;
- private static final String COLUMN_NAME =
- ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME;
- private static final String COLUMN_NUMBER =
- ContactsContract.CommonDataKinds.Phone.NUMBER;
- private static final String COLUMN_NUMBER_TYPE =
- ContactsContract.CommonDataKinds.Phone.TYPE;
- private static final String COLUMN_EMAIL =
- ContactsContract.CommonDataKinds.Email.DATA;
- private static final String COLUMN_EMAIL_TYPE =
- ContactsContract.CommonDataKinds.Email.TYPE;
- private static final String MIMETYPE_STRING_NAME =
- ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE;
- private static final String MIMETYPE_STRING_PHONE =
- ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
- private static final String MIMETYPE_STRING_EMAIL =
- ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
- public ContactsManager(ContentResolver contentResolver) {
- this.contentResolver = contentResolver;
- }
- /**
- * Search and fill the contact information by the contact name given.
- * @param contact Only the name is necessary.
- */
- public Contact searchContact(String name) {
- Log.w(TAG, "**search start**");
- Contact contact = new Contact();
- contact.setName(name);
- Log.d(TAG, "search name: " + contact.getName());
- String id = getContactID(contact.getName());
- contact.setId(id);
- if(id.equals("0")) {
- Log.d(TAG, contact.getName() + " not exist. exit.");
- } else {
- Log.d(TAG, "find id: " + id);
- //Fetch Phone Number
- Cursor cursor = contentResolver.query(
- android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
- new String[]{COLUMN_NUMBER, COLUMN_NUMBER_TYPE},
- COLUMN_CONTACT_ID + "='" + id + "'", null, null);
- while(cursor.moveToNext()) {
- contact.setNumber(cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER)));
- contact.setNumberType(cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER_TYPE)));
- Log.d(TAG, "find number: " + contact.getNumber());
- Log.d(TAG, "find numberType: " + contact.getNumberType());
- }
- //cursor.close();
- //Fetch email
- cursor = contentResolver.query(
- android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI,
- new String[]{COLUMN_EMAIL, COLUMN_EMAIL_TYPE},
- COLUMN_CONTACT_ID + "='" + id + "'", null, null);
- while(cursor.moveToNext()) {
- contact.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL)));
- contact.setEmailType(cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL_TYPE)));
- Log.d(TAG, "find email: " + contact.getEmail());
- Log.d(TAG, "find emailType: " + contact.getEmailType());
- }
- cursor.close();
- }
- Log.w(TAG, "**search end**");
- return contact;
- }
- /**
- *
- * @param contact The contact who you get the id from. The name of
- * the contact should be set.
- * @return 0 if contact not exist in contacts list. Otherwise return
- * the id of the contact.
- */
- public String getContactID(String name) {
- String id = "0";
- Cursor cursor = contentResolver.query(
- android.provider.ContactsContract.Contacts.CONTENT_URI,
- new String[]{android.provider.ContactsContract.Contacts._ID},
- android.provider.ContactsContract.Contacts.DISPLAY_NAME +
- "='" + name + "'", null, null);
- if(cursor.moveToNext()) {
- id = cursor.getString(cursor.getColumnIndex(
- android.provider.ContactsContract.Contacts._ID));
- }
- return id;
- }
- /**
- * You must specify the contact's ID.
- * @param contact
- * @throws Exception The contact's name should not be empty.
- */
- public void addContact(Contact contact) {
- Log.w(TAG, "**add start**");
- ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
- String id = getContactID(contact.getName());
- if(!id.equals("0")) {
- Log.d(TAG, "contact already exist. exit.");
- } else if(contact.getName().trim().equals("")){
- Log.d(TAG, "contact name is empty. exit.");
- } else {
- ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
- .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
- .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
- .build());
- ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(COLUMN_RAW_CONTACT_ID, 0)
- .withValue(COLUMN_MIMETYPE, MIMETYPE_STRING_NAME)
- .withValue(COLUMN_NAME, contact.getName())
- .build());
- Log.d(TAG, "add name: " + contact.getName());
- if(!contact.getNumber().trim().equals("")) {
- ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(COLUMN_RAW_CONTACT_ID, 0)
- .withValue(COLUMN_MIMETYPE, MIMETYPE_STRING_PHONE)
- .withValue(COLUMN_NUMBER, contact.getNumber())
- .withValue(COLUMN_NUMBER_TYPE, contact.getNumberType())
- .build());
- Log.d(TAG, "add number: " + contact.getNumber());
- }
- if(!contact.getEmail().trim().equals("")) {
- ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
- .withValueBackReference(COLUMN_RAW_CONTACT_ID, 0)
- .withValue(COLUMN_MIMETYPE, MIMETYPE_STRING_EMAIL)
- .withValue(COLUMN_EMAIL, contact.getEmail())
- .withValue(COLUMN_EMAIL_TYPE, contact.getEmailType())
- .build());
- Log.d(TAG, "add email: " + contact.getEmail());
- }
- try {
- contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
- Log.d(TAG, "add contact success.");
- } catch (Exception e) {
- Log.d(TAG, "add contact failed.");
- Log.e(TAG, e.getMessage());
- }
- }
- Log.w(TAG, "**add end**");
- }
- /**
- * Delete contacts who's name equals contact.getName();
- * @param contact
- */
- public void deleteContact(Contact contact) {
- Log.w(TAG, "**delete start**");
- ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
- String id = getContactID(contact.getName());
- //delete contact
- ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
- .withSelection(ContactsContract.RawContacts.CONTACT_ID+"="+id, null)
- .build());
- //delete contact information such as phone number,email
- ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
- .withSelection(COLUMN_CONTACT_ID + "=" + id, null)
- .build());
- Log.d(TAG, "delete contact: " + contact.getName());
- try {
- contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
- Log.d(TAG, "delete contact success");
- } catch (Exception e) {
- Log.d(TAG, "delete contact failed");
- Log.e(TAG, e.getMessage());
- }
- Log.w(TAG, "**delete end**");
- }
- /**
- * @param contactOld The contact wants to be updated. The name should exists.
- * @param contactNew
- */
- public void updateContact(Contact contactOld, Contact contactNew) {
- Log.w(TAG, "**update start**");
- String id = getContactID(contactOld.getName());
- if(id.equals("0")) {
- Log.d(TAG, contactOld.getName()+" not exist.");
- } else if(contactNew.getName().trim().equals("")){
- Log.d(TAG, "contact name is empty. exit.");
- } else if(!getContactID(contactNew.getName()).equals("0")){
- Log.d(TAG, "new contact name already exist. exit.");
- } else {
- ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
- //update name
- ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
- .withSelection(COLUMN_CONTACT_ID + "=? AND " + COLUMN_MIMETYPE + "=?",
- new String[]{id, MIMETYPE_STRING_NAME})
- .withValue(COLUMN_NAME, contactNew.getName())
- .build());
- Log.d(TAG, "update name: " + contactNew.getName());
- //update number
- if(!contactNew.getNumber().trim().equals("")) {
- ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
- .withSelection(COLUMN_CONTACT_ID + "=? AND " + COLUMN_MIMETYPE + "=?",
- new String[]{id, MIMETYPE_STRING_PHONE})
- .withValue(COLUMN_NUMBER, contactNew.getNumber())
- .withValue(COLUMN_NUMBER_TYPE, contactNew.getNumberType())
- .build());
- Log.d(TAG, "update number: " + contactNew.getNumber());
- }
- //update email if mail
- if(!contactNew.getEmail().trim().equals("")) {
- ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
- .withSelection(COLUMN_CONTACT_ID + "=? AND " + COLUMN_MIMETYPE + "=?",
- new String[]{id, MIMETYPE_STRING_EMAIL})
- .withValue(COLUMN_EMAIL, contactNew.getEmail())
- .withValue(COLUMN_EMAIL_TYPE, contactNew.getEmailType())
- .build());
- Log.d(TAG, "update email: " + contactNew.getEmail());
- }
- try {
- contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
- Log.d(TAG, "update success");
- } catch (Exception e) {
- Log.d(TAG, "update failed");
- Log.e(TAG, e.getMessage());
- }
- }
- Log.w(TAG, "**update end**");
- }
- }
- package com.example.siqi.contacts;
- public class Contact {
- private String email;
- private String emailType;
- private String id;
- private String name;
- private String number;
- private String numberType;
- public Contact(){
- }
- public Contact(Contact contact){
- this.name = contact.getName();
- this.number = contact.getNumber();
- this.numberType = contact.getNumberType();
- this.email = contact.getEmail();
- this.emailType = contact.getEmailType();
- }
- public String getEmail() {
- return email;
- }
- public String getEmailType() {
- return emailType;
- }
- public String getId() {
- return id;
- }
- public String getName() {
- return name;
- }
- public String getNumber() {
- return number;
- }
- public String getNumberType() {
- return numberType;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public void setEmailType(String emailType) {
- this.emailType = emailType;
- }
- public void setId(String id) {
- this.id = id;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void setNumber(String number) {
- this.number = number;
- }
- public void setNumberType(String numberType) {
- this.numberType = numberType;
- }
- }
- package com.example.siqi.contacts;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ContactsManager cm = new ContactsManager(this.getContentResolver());
- cm.searchContact("张一");
- Contact contact = new Contact();
- contact.setName("张一");
- contact.setEmail("test@test.com");
- contact.setNumber("123456789");
- //test addContact
- cm.addContact(contact);
- cm.searchContact("张一");
- //test updateContact
- Contact contactNew = new Contact(contact);
- contactNew.setName("张二");
- contactNew.setNumber("987654321");
- contactNew.setEmail("newEmail@test");
- cm.updateContact(contact, contactNew);
- cm.searchContact("张一");
- cm.searchContact("张二");
- //test deleteContact
- cm.deleteContact(contactNew);
- cm.searchContact("张二");
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
结果:
- 11-07 15:20:00.873: W/ContactsManager(30113): **search start**
- 11-07 15:20:00.873: D/ContactsManager(30113): search name: 张一
- 11-07 15:20:00.943: D/ContactsManager(30113): 张一 not exist. exit.
- 11-07 15:20:00.943: W/ContactsManager(30113): **search end**
- 11-07 15:20:00.943: W/ContactsManager(30113): **add start**
- 11-07 15:20:00.973: D/ContactsManager(30113): add name: 张一
- 11-07 15:20:01.004: D/ContactsManager(30113): add number: 123456789
- 11-07 15:20:01.004: D/ContactsManager(30113): add email: test@test.com
- 11-07 15:20:01.224: D/ContactsManager(30113): add contact success.
- 11-07 15:20:01.224: W/ContactsManager(30113): **add end**
- 11-07 15:20:01.224: W/ContactsManager(30113): **search start**
- 11-07 15:20:01.224: D/ContactsManager(30113): search name: 张一
- 11-07 15:20:01.243: D/ContactsManager(30113): find id: 30
- 11-07 15:20:01.273: D/ContactsManager(30113): find number: 123456789
- 11-07 15:20:01.273: D/ContactsManager(30113): find numberType: null
- 11-07 15:20:01.323: D/ContactsManager(30113): find email: test@test.com
- 11-07 15:20:01.323: D/ContactsManager(30113): find emailType: null
- 11-07 15:20:01.334: W/ContactsManager(30113): **search end**
- 11-07 15:20:01.334: W/ContactsManager(30113): **update start**
- 11-07 15:20:01.393: D/ContactsManager(30113): update name: 张二
- 11-07 15:20:01.403: D/ContactsManager(30113): update number: 987654321
- 11-07 15:20:01.403: D/ContactsManager(30113): update email: newEmail@test
- 11-07 15:20:01.723: D/ContactsManager(30113): update success
- 11-07 15:20:01.723: W/ContactsManager(30113): **update end**
- 11-07 15:20:01.723: W/ContactsManager(30113): **search start**
- 11-07 15:20:01.723: D/ContactsManager(30113): search name: 张一
- 11-07 15:20:01.743: D/ContactsManager(30113): 张一 not exist. exit.
- 11-07 15:20:01.743: W/ContactsManager(30113): **search end**
- 11-07 15:20:01.743: W/ContactsManager(30113): **search start**
- 11-07 15:20:01.754: D/ContactsManager(30113): search name: 张二
- 11-07 15:20:01.773: D/ContactsManager(30113): find id: 30
- 11-07 15:20:01.803: D/ContactsManager(30113): find number: 987654321
- 11-07 15:20:01.813: D/ContactsManager(30113): find numberType: null
- 11-07 15:20:01.844: D/ContactsManager(30113): find email: newEmail@test
- 11-07 15:20:01.844: D/ContactsManager(30113): find emailType: null
- 11-07 15:20:01.853: W/ContactsManager(30113): **search end**
- 11-07 15:20:01.853: W/ContactsManager(30113): **delete start**
- 11-07 15:20:01.874: D/ContactsManager(30113): delete contact: 张二
- 11-07 15:20:01.953: D/ContactsManager(30113): delete contact success
- 11-07 15:20:01.953: W/ContactsManager(30113): **delete end**
- 11-07 15:20:01.953: W/ContactsManager(30113): **search start**
- 11-07 15:20:01.953: D/ContactsManager(30113): search name: 张二
- 11-07 15:20:01.973: D/ContactsManager(30113): 张二 not exist. exit.
- 11-07 15:20:01.973: W/ContactsManager(30113): **search end**
源代码中的Log.d以及Log.w是android输出日志的API,就当作System.out吧。
这这是一段简单的示例。在android中,同一个联系人可以对应多个号码和邮件,当然也还有其他的信息,比如邮编地址,webpage等等,这些都没有在这里实现。在这里,默认每个联系人只有一个号码和一个邮件。
对联系人的添加/更新,只需要添加/更新数据(name,number,email)到表data就可以了,data表的结构:
系统会自动的在raw_contacts,和contacts添加/更新联系人的ID和NAME以及其他的信息。
删除要删除表raw_contacts和表data的相应数据。但是在删除后发现data表的数据可以删除,但是raw_contacts的数据没有删除,只是一些标志位改变了,例如raw_contact_id变成了空。
另:我试了很多方式,试图删除raw_contacts的记录,但是没有成功。希望有谁知道怎么删除的告诉我。
http://blog.youkuaiyun.com/wssiqi/article/details/8157399