android中ContentResolver的使用

   使用ContentResolver增删改查电话本信息,详细代码如下:

import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ListAdapter;

public class MainActivity extends ListActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		insert("tester1");
		update("tester2", new String(People.NAME + "='tester1'"));
		delete(new String(People.NAME + "='tester2'"));
		select();
	}

	/*
	 * 向联系人列表中插入新的联系人
	 * @param name The value of People.NAME
	 */
	public void insert(String name) {
		ContentValues ct = new ContentValues();
		ct.put(People.NAME, name);
		getContentResolver().insert(People.CONTENT_URI, ct);
	}
  
	/*
	 * 更新手机中指定的联系人
	 * @param name A new name for People.NAME
	 * @param where The update requirement.
	 */
	public void update(String name, String where) {
		ContentValues ct = new ContentValues();
		ct.put(People.NAME, name);
		getContentResolver().update(People.CONTENT_URI, ct, where, null);
	}

	/*
	 * 删除手机中指定的联系人
	 * @param where The delete requirement.
	 */
	public void delete(String where) {
		getContentResolver().delete(People.CONTENT_URI, where, null);
	}

	// 查找所有联系人
	public void select() {
		Cursor cursor = getContentResolver().query(People.CONTENT_URI,
				new String[] { People._ID, People.NAME }, null, null, null);

		ListAdapter adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, cursor,
				new String[] { People.NAME }, new int[] { android.R.id.text1 });

		setListAdapter(adapter);
	}
}

   AndroidManifest.xml中添加如下权限:

<uses-permission android:name="android.permission.READ_CONTACTS"/>
 <uses-permission android:name="android.permission.WRITE_CONTACTS"/>

   

相关推荐