Android――contentProvider(二) 通过ContentResolver访问

public class MyTest extends AndroidTestCase {

	public MyTest() {
		// TODO Auto-generated constructor stub
	}

	public void insert() {
		// 访问内容提供者的步骤:
		// 1、需要一个内容解析者
		ContentResolver contentResolver = getContext().getContentResolver();
		// 使用content://+授权路径
		Uri url = Uri
				.parse("content://com.example.android_contentprovider2.StudentProvider/student");
		ContentValues values = new ContentValues();
		values.put("name", "王五");
		values.put("address", "广西");
		contentResolver.insert(url, values);
	}

	public void delete() {
		ContentResolver contentResolver = getContext().getContentResolver();
		// 删除单行记录,如果要删除多行记录:content://com.example.android_contentprovider2.StudentProvider/student
		Uri uri = Uri
				.parse("content://com.example.android_contentprovider2.StudentProvider/student/1");
		contentResolver.delete(uri, null, null);
	}

	public void update() {
		ContentResolver contentResolver = getContext().getContentResolver();
		Uri uri = Uri
				.parse("content://com.example.android_contentprovider2.StudentProvider/student/2");
		ContentValues values = new ContentValues();
		values.put("name", "李斯");
		values.put("address", "上海");
		contentResolver.update(uri, values, null, null);
	}

	public void query() {
		ContentResolver contentResolver = getContext().getContentResolver();
		// 查询单条记录:content://com.example.android_contentprovider2.StudentProvider/student/2
		// 查询多条记录:content://com.example.android_contentprovider2.StudentProvider/student
		Uri uri = Uri
				.parse("content://com.example.android_contentprovider2.StudentProvider/student");
		// select * from student where id = 2;
		Cursor cursor = contentResolver.query(uri, null, null, null, null);
		while (cursor.moveToNext()) {
			System.out.println("---->>"
					+ cursor.getString(cursor.getColumnIndex("name")));
		}
	}
}


你可能感兴趣的:(contentresolver)