Android entry: add, delete, modify, and query the address book

Source: Internet
Author: User


I. Introduction to address book applications

The address book application is an app that comes with Android. When we see this application, we only think it is an application and store data in a database, but this is not actually the case.
The address book is an application of ContentProvider. The address book consists of two parts:
(1) ContentProvider of com. android. providers. contacts: ContentProvider that truly stores data
(2) com. android. contacts: Use ContentResolver to obtain the data's graphical user interface;

2. Obtain the source code of ContactProvider

Android source code: http://my.oschina.net/zhanglubing/blog/40623 get with git;
If you want to obtain ContactProvider, install git, open git bash, and enter
Git clone https://android.googlesource.com/platform/packages/providers/ContactsProvider.git;
The directory structure is as follows:

Why obtain the source code of ContactProvider?
If you want to access ContentProvider, you must understand the URI settings (authority, path, and so on). Only the source code can be viewed;
AndroidManifest. xml is a list file that lists the authorities of ContactProvider and the permissions required to access the address book;
[Html]
<Uses-permission android: name = "android. permission. READ_CONTACTS"/>
<Uses-permission android: name = "android. permission. WRITE_CONTACTS"/>

The main address book program is ContactsProvider2.java, and the authorities are contacts or com. android. contacts;

Iii. Database Structure of address book

The table structure is as follows:

 



The address book is stored in/data/com. android. providers. contacts/databases/contacts2.db. The main tables are:
(1) raw_contacts: store the contact ID,
The _ id attribute is the primary key and declared as autoincrement. That is, you do not need to manually set other attributes;
The display_name attribute is name;
(2) mimetypes: the type of data to be stored, for example, "vnd. android. cursor. item/name "indicates" name "type data," vnd. android. cursor. item/phone_v2 "indicates telephone data;
(3) data: stores specific data;
The raw_contact_id attribute is used to connect to the raw_contacts table. Each record represents a specific data. Our main data (such as email and phone) is stored in the data table;
The data1 attribute stores the total data;
Data2 attributes:
-If this record stores the name, data2 stores the name;
-If this record stores the phone number, data2 stores the phone number, such as mobile phones and household appliances;
-If this record is stored in an organization, data2 is stored in the organization type, such as the company or others;
-If the record storage address is used, the data2 storage type, such as residential and unit;

4. add, delete, modify, and query the address book

Simply put, the address book operation is a normal ContentProvider operation;

1. Query

(1) query the name by phone number

[Java]
// Query the name based on the phone number (if the phone number is in the address book, the name is displayed when the phone number is called)
Public void testReadNameByPhone (){
String phone = "12345678 ";
// Uri = content: // com. android. contacts/data/phones/filter /#
Uri uri = Uri. parse ("content: // com. android. contacts/data/phones/filter/" + phone );
ContentResolver resolver = this. getContext (). getContentResolver ();
Cursor cursor = resolver. query (uri, new String [] {Data. DISPLAY_NAME}, null); // display_name returned from the raw_contact table
If (cursor. moveToFirst ()){
Log. I ("Contacts", "name =" + cursor. getString (0 ));
}
}

(2) query all contacts


[Java]
// Read all contacts in the address book
// Traverse the id in the raw_contact table and obtain data from the data table based on the id.
Public void testReadAll (){
// Uri = content: // com. android. contacts/contacts
Uri uri = Uri. parse ("content: // com. android. contacts/contacts"); // access the raw_contacts table
ContentResolver resolver = this. getContext (). getContentResolver ();
Cursor cursor = resolver. query (uri, new String [] {Data. _ ID}, null); // get the _ id attribute
While (cursor. moveToNext ()){
StringBuilder buf = new StringBuilder ();
Int id = cursor. getInt (0); // obtain the id and search for data in data
Buf. append ("id =" + id );
Uri = Uri. parse ("content: // com. android. contacts/"+ id +"/data "); // if you want to obtain the data corresponding to an id in the data table, the URI is content: // com. android. contacts/#/data
Cursor cursor2 = resolver. query (uri, new String [] {Data. DATA1, Data. MIMETYPE}, null); // data1 stores the total data of each record, and mimetype stores the record type, such as phone and email.
While (cursor2.moveToNext ()){
String data = cursor2.getString (cursor2.getColumnIndex ("data1 "));
If (cursor2.getString (cursor2.getColumnIndex ("mimetype"). equals ("vnd. android. cursor. item/name") {// if the name is
Buf. append (", name =" + data );
}
Else if (cursor2.getString (cursor2.getColumnIndex ("mimetype"). equals ("vnd. android. cursor. item/phone_v2") {// if the phone number is
Buf. append (", phone =" + data );
}
Else if (cursor2.getString (cursor2.getColumnIndex ("mimetype"). equals ("vnd. android. cursor. item/email_v2") {// if it is an email
Buf. append (", email =" + data );
}
Else if (cursor2.getString (cursor2.getColumnIndex ("mimetype"). equals ("vnd. android. cursor. item/postal-address_v2") {// if it is an address
Buf. append (", address =" + data );
}
Else if (cursor2.getString (cursor2.getColumnIndex ("mimetype"). equals ("vnd. android. cursor. item/organization") {// if it is an organizational unit
Buf. append (", organization =" + data );
}
}
String str = buf. toString ();
Log. I ("Contacts", str );
}
}

 

2. Insert

(1) Add data step by step


[Java]
// Add data step by step
Public void testAddContacts (){
// Insert the raw_contacts table and obtain the _ id attribute.
Uri uri = Uri. parse ("content: // com. android. contacts/raw_contacts ");
ContentResolver resolver = this. getContext (). getContentResolver ();
ContentValues values = new ContentValues ();
Long contact_id = ContentUris. parseId (resolver. insert (uri, values ));
// Insert data table
Uri = Uri. parse ("content: // com. android. contacts/data ");
// Add Name
Values. put ("raw_contact_id", contact_id );
Values. put (Data. MIMETYPE, "vnd. android. cursor. item/name ");
Values. put ("data2", "zdong ");
Values. put ("data1", "xzdong ");
Resolver. insert (uri, values );
Values. clear ();
// Add Phone
Values. put ("raw_contact_id", contact_id );
Values. put (Data. MIMETYPE, "vnd. android. cursor. item/phone_v2 ");
Values. put ("data2", "2"); // mobile phone
Values. put ("data1", "87654321 ");
Resolver. insert (uri, values );
Values. clear ();
// Add email
Values. put ("raw_contact_id", contact_id );
Values. put (Data. MIMETYPE, "vnd. android. cursor. item/email_v2 ");
Values. put ("data2", "2"); // Unit
Values. put ("data1", "www.2cto.com ");
Resolver. insert (uri, values );
}

Author: xiazdong

(2) Batch add data

Core code:
(1) ContentProviderOperation operation = ContentProviderOperation. newInsert (uri). withValue ("key", "value"). build ();
(2) resolver. applyBatch ("authorities", operations); // batch submit


[Java]
<Span style = "font-size: 18px;"> public void testAddContactsInTransaction () throws Exception {
Uri uri = Uri. parse ("content: // com. android. contacts/raw_contacts ");
ContentResolver resolver = this. getContext (). getContentResolver ();
ArrayList <ContentProviderOperation> operations = new ArrayList <ContentProviderOperation> ();
// Add a record to the raw_contact table
// Here. withValue ("account_name", null) must be added, otherwise NullPointerException will be thrown.
ContentProviderOperation operation1 = ContentProviderOperation
. NewInsert (uri). withValue ("account_name", null). build ();
Operations. add (operation1 );
// Add data to data
Uri = Uri. parse ("content: // com. android. contacts/data ");
// Add name
ContentProviderOperation operation2 = ContentProviderOperation
. NewInsert (uri). withValueBackReference ("raw_contact_id", 0)
// The second parameter of withValueBackReference indicates the return id of the operation that references operations [0] as this value
. WithValue ("mimetype", "vnd. android. cursor. item/name ")
. WithValue ("data2", "xzdong"). build ();
Operations. add (operation2 );
// Add mobile phone data
ContentProviderOperation operation3 = ContentProviderOperation
. NewInsert (uri). withValueBackReference ("raw_contact_id", 0)
. WithValue ("mimetype", "vnd. android. cursor. item/phone_v2 ")
. WithValue ("data2", "2"). withValue ("data1", "0000000"). build ();
Operations. add (operation3 );
Resolver. applyBatch ("com. android. contacts", operations );
} </Span>

3. Delete


Core Ideas:
(1) first identify the id in the raw_contacts table based on the name;
(2) Delete raw_contact_id in the data table as long as it matches;

[Java]
Public void testDelete () throws Exception {
String name = "xzdong ";
// Calculate the id based on the name
Uri uri = Uri. parse ("content: // com. android. contacts/raw_contacts ");
ContentResolver resolver = this. getContext (). getContentResolver ();
Cursor cursor = resolver. query (uri, new String [] {Data. _ ID}, "display_name =? ", New String [] {name}, null );
If (cursor. moveToFirst ()){
Int id = cursor. getInt (0 );
// Delete the corresponding data in the data according to the id
Resolver. delete (uri, "display_name =? ", New String [] {name });
Uri = Uri. parse ("content: // com. android. contacts/data ");
Resolver. delete (uri, "raw_contact_id =? ", New String [] {id + ""});
}
}


4. Update

Core Ideas:
(1) You do not need to update raw_contacts. You only need to update the data table;
(2) uri = content: // com. android. contacts/data indicates operations on the data table;
[Java]
Public void testUpdate () throws Exception {
Int id = 1;
String phone = "999999 ";
Uri uri = Uri. parse ("content: // com. android. contacts/data"); // all data operations on the data table
ContentResolver resolver = this. getContext (). getContentResolver ();
ContentValues values = new ContentValues ();
Values. put ("data1", phone );
Resolver. update (uri, values, "mimetype =? And raw_contact_id =? ", New String [] {" vnd. android. cursor. item/phone_v2 ", id + ""})
}

Author: xiazdong

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.