自定义ContentProvider

一、定义

1.编写一个类,必须继承自ContentProvider类

2.实现ContentProvider类中所有的抽象方法

3.定义ContentProvider的URI

4.使用UriMatcher对象映射Uri返回代码

5.根据实际的需要编写相应方法

6.在AndroidMainfest.xml文件中使用<provider>标签注册ContentProvider

以下是实现类:

package cn.eoe.region.content.provider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class RegionContentProvider extends ContentProvider
{
	private static UriMatcher uriMatcher;
	private static final String AUTHORITY = "cn.eoe.regioncontentprovider";
	private static final int CITIES = 1;
	private static final int CITY_CODE = 2;
	private static final int CITY_NAME = 3;
	private static final int CITIES_IN_PROVINCE = 4;
	private SQLiteDatabase database;

	static
	{

		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		// content://cn.eoe.regioncontentprovider/cities
		uriMatcher.addURI(AUTHORITY, "cities", CITIES);
		//  content://cn.eoe.regioncontentprovider/code/024
		uriMatcher.addURI(AUTHORITY, "code/#", CITY_CODE);
		//  content://cn.eoe.regioncontentprovider/name/北京
		uriMatcher.addURI(AUTHORITY, "name/*", CITY_NAME);
		//  content://cn.eoe.regioncontentprovider/cities_in_province/辽宁
		uriMatcher
				.addURI(AUTHORITY, "cities_in_province/*", CITIES_IN_PROVINCE);

	}

	private SQLiteDatabase openDatabase()//写入数据库到内存卡根目录
	{
		try
		{
			String databaseFilename = "/sdcard/region.db";
			if (!(new File(databaseFilename)).exists())
			{
				InputStream is = getContext().getResources().getAssets()
						.open("region.db");
				FileOutputStream fos = new FileOutputStream(databaseFilename);
				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) > 0)
				{
					fos.write(buffer, 0, count);
				}

				fos.close();
				is.close();
			}
			SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
					databaseFilename, null);
			return database;
		}
		catch (Exception e)
		{
			Log.d("error", e.getMessage());
		}
		return null;
	}

	@Override
	public boolean onCreate()
	{
		database = openDatabase();
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,//实现查找功能的关键部分
			String[] selectionArgs, String sortOrder)
	{
		Cursor cursor = null;

		switch (uriMatcher.match(uri))
		{
			case CITIES:

				cursor = database.query("v_cities_province", projection,
						selection, selectionArgs, null, null, sortOrder);
				break;
			case CITY_CODE:
				String cityCode = uri.getPathSegments().get(1);
				if (selection == null)
					selection = "city_code='" + cityCode + "'";
				else
					selection += " and (city_code='" + cityCode + "')";
				cursor = database.query("t_cities", projection, selection,
						selectionArgs, null, null, sortOrder);

				break;
			case CITY_NAME:
				String cityName = uri.getPathSegments().get(1);
				if (selection == null)
					selection = "city_name='" + cityName + "'";
				else
					selection += " and (city_name='" + cityName + "')";
				cursor = database.query("t_cities", projection, selection,
						selectionArgs, null, null, sortOrder);

				break;
			case CITIES_IN_PROVINCE:
				String provinceName = uri.getPathSegments().get(1);
				if (selection == null)
					selection = "province_name='" + provinceName + "'";
				else
					selection += " and (province_name='" + provinceName + "')";
				cursor = database.query("v_cities_province", projection, selection,
						selectionArgs, null, null, sortOrder);				
				break;
			
			default:
				throw new IllegalArgumentException("<" + uri + ">格式不正确.");
		}
		return cursor;

	}

	@Override
	public String getType(Uri uri)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs)
	{
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs)
	{
		// TODO Auto-generated method stub
		return 0;
	}

}
URI分为authority和path两部分,其中authority就是
“content://authority”中的authority,相当于网址中的域名,而path
就是“content://authority/”后面的部分,与网址中的路径类似。

二、实现

使用ContentResolver类,获得Uri,查到相关记录并处理。
package cn.eoe.invoke.content.provider;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class Main extends Activity
{
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{  
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
  
	public void onClick_Show_Cities(View view)
	{
		ContentResolver contentResolver = getContentResolver();
		Uri uri = Uri
				.parse("content://cn.eoe.regioncontentprovider/cities");
		Cursor cursor = contentResolver.query(uri, new String[]
		{ "city_code as _id", "city_name", "province_code" }, null, null, null);

		SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, cursor, new String[]
				{ "city_name" }, new int[]
				{ android.R.id.text1 });

		ListView lvCities = (ListView) findViewById(R.id.lvCities);
		lvCities.setAdapter(simpleCursorAdapter);

		uri = Uri
				.parse("content://cn.eoe.regioncontentprovider/code/024");
		cursor = contentResolver.query(uri, null, null, null, null);
		if (cursor.moveToFirst())
		{
			Toast.makeText(
					this,
					"024:"
							+ cursor.getString(cursor
									.getColumnIndex("city_name")),
					Toast.LENGTH_LONG).show();
		}

		uri = Uri
				.parse("content://cn.eoe.regioncontentprovider/name/沈阳");
		cursor = contentResolver.query(uri, null, null, null, null);
		if (cursor.moveToFirst())
		{
			Toast.makeText(
					this,
					"沈阳:"
							+ cursor.getString(cursor
									.getColumnIndex("city_code")),
					Toast.LENGTH_LONG).show();
		}
	}

	public void onClick_Show_Lining_Cities(View view)
	{
		ContentResolver contentResolver = getContentResolver();
		Uri uri = Uri
				.parse("content://cn.eoe.regioncontentprovider/cities_in_province/辽宁");
		Cursor cursor = contentResolver.query(uri, new String[]
		{ "city_code as _id", "city_name", "province_code" }, null, null,
				"city_code");

		SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, cursor, new String[]
				{ "city_name" }, new int[]
				{ android.R.id.text1 });

		ListView lvCities = (ListView) findViewById(R.id.lvCities);
		lvCities.setAdapter(simpleCursorAdapter);
	}
}

总得来说,如果在以后的开发中,有必要可以使用android系统提供的ContentProvider,比如联系人数据,实现更丰富的功能。

你可能感兴趣的:(自定义ContentProvider)