1. 程式人生 > >ContactsContract中Contacts,RawContacts和Data關係圖解及其例項程式碼

ContactsContract中Contacts,RawContacts和Data關係圖解及其例項程式碼

(1)Contacts,RawContacts和Data三者之間的關係

Contacts,RawContacts和Data關係圖大體如下所示:


(2)三個變數的解釋


2.1 ContactsContract.Contacts Constants for the contacts table, which contains a record per aggregate of raw contacts representing the same person. 
2.2 ContactsContract.RawContacts Constants for the raw contacts table, which contains one row of contact information for each person in each synced account.  2.3 ContactsContract.Data
Constants for the data table, which contains data points tied to a raw contact. 

2.4 ContactsContract.CommonDataKinds


Container for definitions of common data types stored in the ContactsContract.Data table. 

(3)例項程式碼

3.1 MainActivity     //主選單Acivity,包括兩個按鈕:一個用於瀏覽手機所有聯絡人資訊,另外一個用於新增聯絡人。 package com.example.contactscontracttest;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

Button viewallcontacts;
Button addcontact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        viewallcontacts = (Button)findViewById(R.id.viewallcontacts);
        addcontact = (Button)findViewById(R.id.addcontact);
        
        viewallcontacts.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, ViewAllContactActivity.class);
startActivity(intent);
}
});
        
        addcontact.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, AddContactActivity.class);
startActivity(intent);
}
});
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
對應的Layout檔案activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/viewallcontacts"
        android:text="View all contacts"
        />
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/addcontact"
        android:text="Add contact"
        />


</LinearLayout>

效果圖:


3.2 ViewAllContactActivity     //顯示手機裡所有聯絡人的資訊,由一個ExpandableListView和Button組成。ExpandableListView用於顯示一個聯絡人名稱和其所有的電話和Email的聯絡方式。按鈕用於返回主選單。

package com.example.contactscontracttest;


import java.util.ArrayList;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;


public class ViewAllContactActivity extends Activity {
ExpandableListView list;
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> phones = new ArrayList<String>();
ArrayList<String> ids = new ArrayList<String>();
ArrayList<String> emails = new ArrayList<String>();
ArrayList<ArrayList<String>> details = new ArrayList<ArrayList<String>>();


ContentResolver resolver;
Cursor cursor;
Button backtomainmenu;



@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_contacts);

resolver = getContentResolver();

//查詢所有聯絡人物件
cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);
while (cursor.moveToNext()) {
//獲取聯絡人的唯一標示ID
long id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String strId = id + "";
ids.add(strId);
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
names.add(name);

ArrayList<String> detail = new ArrayList<String>();

//根據Id查詢該聯絡人的一個或者多個電話
String[] projection = new String [] {
ContactsContract.CommonDataKinds.Phone.NUMBER
};
String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + "?";
String[] selectionArgs = new String [] {strId};
Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, selection, selectionArgs, null);
while (phoneCursor.moveToNext()) {
String num = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phones.add(num);
detail.add(num);
}

//根據Id查詢該聯絡人的email郵箱
String [] proj = new String [] {
ContactsContract.CommonDataKinds.Email.ADDRESS
};
String sel = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + "?";
String[] selArg = new String [] {strId}; 
Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, proj, sel, selArg, null);
while (emailCursor.moveToNext()) {
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
emails.add(email);
detail.add(email);
}

details.add(detail);
}


list = (ExpandableListView)findViewById(R.id.expandablelistview);

ExpandableListAdapter adapter = new BaseExpandableListAdapter() {

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}

@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView textView = new TextView(ViewAllContactActivity.this);
textView.setText(names.get(groupPosition).toString());
LayoutParams lyParams = new LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(lyParams);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
textView.setPadding(36, 0, 0, 0);
//textView.setTextSize(20);

return textView;
}

@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}

@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return names.size();
}

@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return names.get(groupPosition);
}

@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return details.get(groupPosition).size();
}

@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView textView = new TextView(ViewAllContactActivity.this);
textView.setText(details.get(groupPosition).get(childPosition).toString());
LayoutParams lyParams = new LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(lyParams);


return textView;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}

@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return details.get(groupPosition).get(childPosition);
}
};

list.setAdapter(adapter);

backtomainmenu = (Button)findViewById(R.id.mainmenu);
backtomainmenu.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(ViewAllContactActivity.this, MainActivity.class);
startActivity(intent);
}
});
}



}

對應的Layout檔案all_contacts.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <ExpandableListView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/expandablelistview"
        />
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/mainmenu"
        android:text="Go Mainmenu"
        />


</LinearLayout>

效果圖如下:


3.3 AddContactActivity     //新增聯絡人,由三個EditText和2個Button組成,三個文字框用於新增聯絡人名稱,手機號和email地址,第一個按鈕用於新增聯絡人資訊,第二個按鈕用於返回主選單。

package com.example.contactscontracttest;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class AddContactActivity extends Activity {
EditText addname;
EditText addphone;
EditText addemail;
Button addsubmit;
Button addgotomainmenu;
ContentResolver resolver;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contact);

resolver = getContentResolver();

addname = (EditText)findViewById(R.id.addname);
addphone = (EditText)findViewById(R.id.addphone);
addemail = (EditText)findViewById(R.id.addemail);

addsubmit = (Button)findViewById(R.id.addsubmit);
addgotomainmenu = (Button)findViewById(R.id.addgomainmenu);

//點選返回首頁
addgotomainmenu.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(AddContactActivity.this, MainActivity.class);
startActivity(intent);
}
});

//新增通訊人
addsubmit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String strName = addname.getText().toString();
String strPhone = addphone.getText().toString();
String strEmail = addemail.getText().toString();

//先建立contact ID,再插入詳細資訊
ContentValues values = new ContentValues();
Uri newRawContactUri = resolver.insert(ContactsContract.RawContacts.CONTENT_URI, values);
long id = ContentUris.parseId(newRawContactUri);

//新增名稱
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, id);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, strName);
resolver.insert(ContactsContract.Data.CONTENT_URI, values);

//新增手機號碼
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, id);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, strPhone);
resolver.insert(ContactsContract.Data.CONTENT_URI, values);

//新增郵箱
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, id);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Email.ADDRESS, strEmail);
resolver.insert(ContactsContract.Data.CONTENT_URI, values);

Toast.makeText(AddContactActivity.this, "新增新聯絡人成功", Toast.LENGTH_LONG).show();
}
});
}


}

對應的Layout檔案add_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <EditText 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/addname"
        />
    <EditText 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id = "@+id/addphone"
        />
    <EditText 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/addemail"
        />
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/addsubmit"
        android:text="Add"
        />
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/addgomainmenu"
        android:text="Back to Mainmenu"
        />


</LinearLayout>

對應的效果圖:


(4)程式碼下載

編譯環境 ADT android 4.4,程式碼請見我的百度雲盤: http://pan.baidu.com/s/1bndm2n1