您的位置:首页 > 编程语言 > PHP开发

contentprovider管理联系人信息

2013-11-07 10:26 211 查看
1.什么是ContentProvider

数据库在Android当中是私有的,当然这些数据包括文件数据和数据库数据以及一些其他类型的数据。

不能将数据库设为WORLD_READABLE,每个数据库都只能创建它的包访问,

这意味着只有由创建数据库的进程可访问它。如果需要在进程间传递数据,

则可以使用AIDL/Binder或创建一个ContentProvider,但是不能跨越进程/包边界直接来使用数据库。

一个Content Provider类实现了一组标准的方法接口,从而能够让其他的应用保存或读取此Content Provider的各种数据类型。

也就是说,一个程序可以通过实现一个Content Provider的抽象接口将自己的数据暴露出去。

外界根本看不到,也不用看到这个应用暴露的数据在应用当中是如何存储的,或者是用数据库存储还是用文件存储,还是通过网上获得,这些一切都不重要,

重要的是外界可以通过这一套标准及统一的接口和程序里的数据打交道,可以读取程序的数据,也可以删除程序的数据,

当然,中间也会涉及一些权限的问题。下边列举一些较常见的接口,这些接口如下所示。

· query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder):通过Uri进行查询,返回一个Cursor。

· insert(Uri url, ContentValues values):将一组数据插入到Uri 指定的地方。

· update(Uri uri, ContentValues values, String where, String[] selectionArgs):更新Uri指定位置的数据。

· delete(Uri url, String where, String[] selectionArgs):删除指定Uri并且符合一定条件的数据。

2.什么是ContentResolver

外界的程序通过ContentResolver接口可以访问ContentProvider提供的数据,在Activity当中通过getContentResolver()可以得到当前应用的 ContentResolver实例。

ContentResolver提供的接口和ContentProvider中需要实现的接口对应,主要有以下几个。

· query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder):通过Uri进行查询,返回一个Cursor。

· insert(Uri url, ContentValues values):将一组数据插入到Uri 指定的地方。

· update(Uri uri, ContentValues values, String where, String[] selectionArgs):更新Uri指定位置的数据。

· delete(Uri url, String where, String[] selectionArgs):删除指定Uri并且符合一定条件的数据。

3.ContentProvider和ContentResolver中用到的Uri

在ContentProvider和 ContentResolver当中用到了Uri的形式通常有两种,一种是指定全部数据,另一种是指定某个ID的数据。

我们看下面的例子。

· content://contacts/people/ 这个Uri指定的就是全部的联系人数据。

· content://contacts/people/1 这个Uri指定的是ID为1的联系人的数据。

在上边两个类中用到的Uri一般由3部分组成。

· 第一部分是方案:"content://" 这部分永远不变

· 第二部分是授权:"contacts"

· 第二部分是路径:"people/","people/1"(如果没有指定ID,那么表示返回全部)。

由于URI通常比较长,而且有时候容易出错,且难以理解。所以,在Android当中定义了一些辅助类,并且定义了一些常量来代替这些长字符串的使用,例如下边的代码:

· Contacts.People.CONTENT_URI (联系人的URI)。

在我们的实例MyProvider中是如下定义的:

public static final String AUTHORITY="com.teleca.PeopleProvider";

public static final String PATH_SINGLE="people/#";

public static final String PATH_MULTIPLE="people";

public static final Uri content_URI=Uri.parse("content://"+AUTHORITY+"/"+PATH_MULTIPLE);

如果是ContentProvider是内容提供者的话,那么ContentResolver就是内容提取者,它负责从ContentProvider中提取或处理数据。 ContentResolver通过uri告诉ContentProvider需要获取或处理哪些数据。如果要实现ContentProvider那么需要继承ContentProvider并重写其中的抽象方法:

方 法 名 称
方 法 描 述
insert(Uri,ContentValues)
插入
delete(Uri,String,String[])
删除
update(Uri,ContentValues,String,String[])
修改
query(Uri,String[],String,String[],Stting)
查询
getType(Uri)
获得MIME数据类型
onCreate()
当ContentProvider创建时调用
getContext()
获得Context对象
•我们是在ContentProvider中实现我们实际操作数据的方法的。但是,客户端调用时,我们用到了另外的一个接口,它就是ContenResolver。ContentResolver中提供和ContentProvider中对应的方法。我们是间接地通过操作ContentResolver来操作ContentProvider的。

•ContentResolver通过应用程序的getContentResolver()方法获得。一般情况下,ContentProvider是单实例的,但是可以有多个ContentResolver在不同的应用程序和不同的进程之间和ContentProvider交互。

方 法 名 称
方 法 描 述
insert(Uri,ContentValues)
插入
delete(Uri,String,String[])
删除
update(Uri,ContentValues,String,String[])
修改
query(Uri,String[],String,String[],Stting)
查询
URL:

•ContentProvider又是如何共享其数据的呢?这里就要知道另外的一个概念,这便是URI。ContentProvider就是通过该对象来共享其数据的。

•一个URI对象必须以“content://”开头,接下来是URI的授权部分,这部分内容要和AndroidManifest.xml配置文件中声明的授权内容一致,后面还可能有数据类型和记录ID。

•通过URI可以使得ContentResolver知道和哪个ContentProvider对应,并且来操作哪些表以及记录。





•ContentResolver操作数据的步骤只需两步:

–1.调用Activity的getContentResolver()获取ContentResolver对象。

–2.根据需要调用ContentResolver的insert()、delete()、update()、query()方法操作数据。
为了操作系统提供的ContentResolver,只需了解该ContentProvider的Uri即可

example:

管理联系人部分代码:

Android系统提供了Contact应用程序来管理联系人,其中用到的Uri如下:

ContactsContract.Contacts.CONTENT_URI:管理联系人的Uri。

ContactsContract.CommonDataKinds.Phone.CONTENT_URI:管理联系人的电话Uri。

ContactsContract.CommonDataKinds.Email.CONTENT_URI:管理联系人的Email的Uri

//使用ContentResolver查找联系人数据

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

//获取联系人ID

String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

//获取联系人的姓名

String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

//根据联系人的ID查找该联系人下的所有电话

Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{contactId}, null);

while(phoneCursor.moveToNext()){

String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

infoList.add("电话号码:"+phoneNumber);

}

//根据联系人的ID查找该联系人下的所有Email

Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[]{contactId}, null);

while(emailCursor.moveToNext()){

String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

infoList.add("mail:"+email);

}

ContentValues values = new ContentValues();

//向RawContacts插入一个空值,目的为了得到增加联系人的ID

Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);

//获取Uri中的id

long rawContactId = ContentUris.parseId(rawContactUri);

//增加姓名

values.clear();

//指定此姓名相关联的联系人ID

values.put(Data.RAW_CONTACT_ID, rawContactId);

//设置添加姓名的MIME类型

values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);

//设置添加的姓名为该联系人的姓名

values.put(StructuredName.GIVEN_NAME, name);

getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

//增加电话

values.clear();

//指定此电话相关联的联系人ID

values.put(Data.RAW_CONTACT_ID, rawContactId);

//设置添加电话的MIME类型

values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);

//设置添加电话属于什么类型(手机、住宅或办公等等)

values.put(Phone.TYPE,Phone.TYPE_MOBILE);

//设置添加的电话为该联系人的电话

values.put(Phone.NUMBER, phone);

getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

//增加email

values.clear();

//指定此email相关联的联系人ID

values.put(Data.RAW_CONTACT_ID, rawContactId);

//设置添加email的MIME类型

values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);

//设置添加email属于什么类型(家用或办公等等)

values.put(Email.TYPE,Email.TYPE_WORK);

//设置添加的email为该联系人的email

values.put(Email.DATA, email);

getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

这一部分是总体UI布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<LinearLayout 
	android:orientation="horizontal"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:gravity="center_horizontal"
	>
<Button 
	android:id="@+id/search"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="@string/search"
	/>
<Button 
	android:id="@+id/add"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="@string/add"
	/>	
</LinearLayout>	
<TextView  
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:text="@string/name"
	/>
<EditText
	android:id="@+id/name"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	/>	
<TextView  
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:text="@string/phone"
	/>
<EditText
	android:id="@+id/phone"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:phoneNumber="true"
	/>	
<TextView  
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:text="@string/email"
	/>
<EditText
	android:id="@+id/email"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	/>			
</LinearLayout>

然后查询结果的布局

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<ExpandableListView
	android:id="@+id/list"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:childIndicator="@drawable/icon"
	/>
</LinearLayout>


为查询和添加按钮增加监听器

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContacts.Data;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

 class ContactProviderTest extends Activity
{
	Button search;
	Button add;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取系统界面中查找、添加两个按钮
		search = (Button) findViewById(R.id.search);
		add = (Button) findViewById(R.id.add);
		search.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View source)
			{
				// 定义两个List来封装系统的联系人信息、指定联系人的电话号码、Email等详情
				final ArrayList<String> names = new ArrayList<String>();
				final ArrayList<ArrayList<String>> details
					= new ArrayList<ArrayList<String>>();
				// 使用ContentResolver查找联系人数据
				Cursor cursor = getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI
					, null, null, null, null);				
				// 遍历查询结果,获取系统中所有联系人
				while (cursor.moveToNext())
				{
					// 获取联系人ID
					String contactId = cursor.getString(cursor
						.getColumnIndex(ContactsContract.Contacts._ID));
					// 获取联系人的名字
					String name = cursor.getString(cursor
						.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					names.add(name);
					// 使用ContentResolver查找联系人的电话号码
					Cursor phones = getContentResolver().query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null,
						ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
							+ " = " + contactId, null, null);
					ArrayList<String> detail = new ArrayList<String>();
					// 遍历查询结果,获取该联系人的多个电话号码
					while (phones.moveToNext())
					{
						// 获取查询结果中电话号码列中数据。
						String phoneNumber = phones
							.getString(phones
							.getColumnIndex(ContactsContract
							.CommonDataKinds.Phone.NUMBER));
						detail.add("电话号码:" + phoneNumber); 
					}
					phones.close();
					// 使用ContentResolver查找联系人的Email地址
					Cursor emails = getContentResolver().query(
						ContactsContract.CommonDataKinds.Email.CONTENT_URI,
						null,
						ContactsContract.CommonDataKinds.Email.CONTACT_ID 
							+ " = " + contactId, null, null);
					// 遍历查询结果,获取该联系人的多个Email地址
					while (emails.moveToNext())
					{
						// 获取查询结果中Email地址列中数据。
						String emailAddress = emails
							.getString(emails
							.getColumnIndex(ContactsContract
							.CommonDataKinds.Email.DATA));
						detail.add("邮件地址:" + emailAddress); 
					}
					emails.close();
					details.add(detail);
				}
				cursor.close();
				//加载result.xml界面布局代表的视图
				View resultDialog = getLayoutInflater().inflate(
					R.layout.result, null);	
				// 获取resultDialog中ID为list的ExpandableListView
				ExpandableListView list = (ExpandableListView)resultDialog
					.findViewById(R.id.list);
				//创建一个ExpandableListAdapter对象
				ExpandableListAdapter adapter = new BaseExpandableListAdapter()
				{
					//获取指定组位置、指定子列表项处的子列表项数据
					@Override
					public Object getChild(int groupPosition, int childPosition)
					{
						return details.get(groupPosition).get(childPosition);
					}
					@Override
					public long getChildId(int groupPosition, int childPosition)
					{
						return childPosition;
					}
					@Override
					public int getChildrenCount(int groupPosition)
					{
						return details.get(groupPosition).size();
					}
					private TextView getTextView()
					{
						AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
								ViewGroup.LayoutParams.FILL_PARENT, 64);
						TextView textView = new TextView(ContactProviderTest.this);
						textView.setLayoutParams(lp);
						textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
						textView.setPadding(36, 0, 0, 0);
						textView.setTextSize(20);
						return textView;
					}
					// 该方法决定每个子选项的外观
					@Override
					public View getChildView(int groupPosition, int childPosition,
							boolean isLastChild, View convertView, ViewGroup parent)
					{
						TextView textView = getTextView();	
						textView.setText(getChild(groupPosition, childPosition).toString());
						return textView;
					}
					//获取指定组位置处的组数据
					@Override
					public Object getGroup(int groupPosition)
					{
						return names.get(groupPosition);
					}
					@Override
					public int getGroupCount()
					{
						return names.size();
					}
					@Override
					public long getGroupId(int groupPosition)
					{
						return groupPosition;
					}
					//该方法决定每个组选项的外观
					@Override
					public View getGroupView(int groupPosition, boolean isExpanded,
							View convertView, ViewGroup parent)
					{
						TextView textView = getTextView();
						textView.setText(getGroup(groupPosition).toString());
						return textView;
					}
					@Override
					public boolean isChildSelectable(int groupPosition, int childPosition)
					{
						return true;
					}
					@Override
					public boolean hasStableIds()
					{
						return true;
					}
				};
				// 为ExpandableListView设置Adapter对象
				list.setAdapter(adapter);
				// 使用对话框来显示查询结果。
				new AlertDialog.Builder(ContactProviderTest.this)
					.setView(resultDialog)
					.setPositiveButton("确定" , null)
					.show();				
			}
		});
		// 为add按钮的单击事件绑定监听器
		add.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 获取程序界面中的3个文本框
				String name = ((EditText)findViewById(R.id.name))
					.getText().toString();
				String phone = ((EditText)findViewById(R.id.phone))
					.getText().toString();
				String email = ((EditText)findViewById(R.id.email))
					.getText().toString();
				// 创建一个空的ContentValues
				ContentValues values = new ContentValues();
				// 向RawContacts.CONTENT_URI执行一个空值插入,
				// 目的是获取系统返回的rawContactId 
				Uri rawContactUri = getContentResolver()
					.insert(RawContacts.CONTENT_URI, values);
				long rawContactId = ContentUris.parseId(rawContactUri);
				values.clear();
				values.put(Data.RAW_CONTACT_ID, rawContactId); 
				// 设置内容类型
				values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
				// 设置联系人名字
				values.put(StructuredName.GIVEN_NAME, name);
				// 向联系人URI添加联系人名字
				getContentResolver().insert(
					android.provider.ContactsContract.Data.CONTENT_URI, values);
				values.clear();
				values.put(Data.RAW_CONTACT_ID, rawContactId);
				values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
				// 设置联系人的电话号码
				values.put(Phone.NUMBER, phone);
				// 设置电话类型
				values.put(Phone.TYPE, Phone.TYPE_MOBILE);
				// 向联系人电话号码URI添加电话号码
				getContentResolver().insert(
					android.provider.ContactsContract.Data.CONTENT_URI, values);
				values.clear();
				values.put(Data.RAW_CONTACT_ID, rawContactId);
				values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
				// 设置联系人的Email地址
				values.put(Email.DATA, email);
				// 设置该电子邮件的类型
				values.put(Email.TYPE, Email.TYPE_WORK);
				// 向联系人Email URI添加Email数据
				getContentResolver().insert(
					android.provider.ContactsContract.Data.CONTENT_URI, values);
				Toast.makeText(ContactProviderTest.this
					, "联系人数据添加成功" , 8000)
					.show();
			}
		});
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: