android ContentProvider解析使用

一.1.ContentProvider为存储数据提供了统一的接口,使用ContentProvider可以使应用程序实现数据的共享
    2.每隔ContentProvider都拥有一个公共的URI叫做CONTENT_URI;用于表示ContentProvider所提供的数据
    3.ContentProvider提供以下函数query(),    insert();     update();     delete();    getType();    onCreate();(oncreate()函数在ContentProvider启动的时候,进行启动);
    4.实现ContentProvider的过程
        4.1定义一个CONTENT_URI常量,用于访问ContentProvider;
        4.2定义一个类,继承ContentProvider
        4.3实现其函数insert();update();delete();query();getType();onCreate();
        4.4不要忘记在AndroidManifest.xml中声明

下面这个类是对ContentProvider的一些定义

package net.androidla.contentprovider;

import android.net.Uri;
import android.provider.BaseColumns;

public class MyContentProviderMetaData {
	public static final String AUTHORIY = "net.androidla.contentprovider.MyContentProvider";
	public static final String DATABASE_NAME = "androidla.db";
	public static final int DATABASE_VERSION = 1;
	public static final String USERS_TABLE_NAME = "users";
	
	public static final class UserTableMetaData implements BaseColumns {
		public static final String TABLE_NAME = "users";
		public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORIY + "/users");
		public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.mycontentprovider.user";
		public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.mycontentprovider.user";
		public static final String USER_NAME = "name";
		public static final String DEFAULT_SORT_ORDER = "_id desc";
	}
}



5.URI类简介
Uri代表了要操作的数据,Uri主要包含两部分信息,1是需要操作的ContentProvider,2对ContentProvider的什么数据进行操作。一个Uri有以下几部分,5.1 schemeContentProvider(内容提供者)的scheme已经由Android所规定为:content://
            5.2 主机名(或Authority):用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它。

            5.3路径(path):可以用来表示我们要操作的数据,路径的构建应根据业务而定,如下:

        要操作contact表中id10的记录,可以构建这样的路径:/contact/10
      要操作contact表中id10的记录的name字段, contact/10/name
        要操作contact表中的所有记录,可以构建这样的路径:/contact


这个是ContentProvider


package net.androidla.contentprovider;

import java.util.HashMap;

import net.androidla.contentprovider.MyContentProviderMetaData.UserTableMetaData;
import net.androidla.databasehelper.SqliteHelper;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class MyContentProvider extends ContentProvider {
	public static final UriMatcher uriMatcher;
	public static final int INCOMING_USER_COLLECTION = 1;
	public static final int INCOMING_USER_SINGLE = 2;
	private SqliteHelper sqliteHelper;
	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(MyContentProviderMetaData.AUTHORIY, "users", INCOMING_USER_COLLECTION);
		uriMatcher.addURI(MyContentProviderMetaData.AUTHORIY, "users/#", INCOMING_USER_SINGLE);
	}
	public static HashMap<String, String> userProjectionMap;
	static {
		userProjectionMap = new HashMap<String, String>();
		userProjectionMap.put(UserTableMetaData._ID, UserTableMetaData._ID);
		userProjectionMap.put(UserTableMetaData.USER_NAME, UserTableMetaData.USER_NAME);
	}
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		return 0;
	}
	@Override
	public String getType(Uri uri) {
		switch (uriMatcher.match(uri)) {
		case INCOMING_USER_COLLECTION:
			return UserTableMetaData.CONTENT_TYPE;
		case INCOMING_USER_SINGLE:
			return UserTableMetaData.CONTENT_TYPE_ITEM;
		default:
			throw new IllegalArgumentException("Unknown URI" + uri);
		}
	}
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = sqliteHelper.getWritableDatabase();
		long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);
		if (rowId > 0) {
			Uri insertUserUri = ContentUris.withAppendedId(UserTableMetaData.CONTENT_URI, rowId);
			getContext().getContentResolver().notifyChange(insertUserUri, null);
			return insertUserUri;
		}
		throw new SQLException("failed insert row into " + uri);
	}
	@Override
	public boolean onCreate() {
		sqliteHelper = new SqliteHelper(getContext(), MyContentProviderMetaData.DATABASE_NAME, null, MyContentProviderMetaData.DATABASE_VERSION);
		return true;
	}
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		switch (uriMatcher.match(uri)) {
		case INCOMING_USER_COLLECTION:
			builder.setTables(UserTableMetaData.TABLE_NAME);
			builder.setProjectionMap(userProjectionMap);
			break;
		case INCOMING_USER_SINGLE:
			builder.setTables(UserTableMetaData.TABLE_NAME);
			builder.setProjectionMap(userProjectionMap);
			builder.appendWhere(UserTableMetaData._ID + "=" + uri.getPathSegments().get(1));
			break;
		default :
			builder.setTables(UserTableMetaData.TABLE_NAME);
			builder.setProjectionMap(userProjectionMap);
			break;
		}
		String orderBy;
		if (TextUtils.isEmpty(sortOrder)) {
			orderBy = UserTableMetaData.DEFAULT_SORT_ORDER;
		} else {
			orderBy = sortOrder;
		}
		SQLiteDatabase db = sqliteHelper.getWritableDatabase();
		Cursor c = builder.query(db, projection, selection, selectionArgs, null, null, orderBy);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c; 
	}
	@Override
	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
		return 0;
	}
}


这个是Activity


package net.androidla.test;

import net.androidla.contentprovider.MyContentProviderMetaData;
import net.androidla.contentprovider.MyContentProviderMetaData.UserTableMetaData;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ContentProviderActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button btnInsert = (Button) findViewById(R.id.btnInsert);
        final Button btnQuery = (Button) findViewById(R.id.btnQuery);
        btnInsert.setOnClickListener(onClickListener);
        btnQuery.setOnClickListener(onClickListener);
    }
    private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Button btn = (Button) v;
			switch (btn.getId()) {
			case R.id.btnInsert:
				ContentValues values = new ContentValues();
				values.put(MyContentProviderMetaData.UserTableMetaData.USER_NAME, "test");
				Uri uri = getContentResolver().insert(MyContentProviderMetaData.UserTableMetaData.CONTENT_URI, values);
				Toast.makeText(ContentProviderActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
				break;
			case R.id.btnQuery:
				Cursor c = getContentResolver().query(MyContentProviderMetaData.UserTableMetaData.CONTENT_URI, null, null, null, null);
				StringBuilder strSb = new StringBuilder();
				while(c.moveToNext()) {
					strSb.append(c.getString(c.getColumnIndex(UserTableMetaData.USER_NAME)));
					strSb.append("\r\n");
				}
				Toast.makeText(ContentProviderActivity.this, strSb.toString(), Toast.LENGTH_LONG).show();
				break;
			}
		}
	};
}


还有一个是连接SQLiteDatabase的

package net.androidla.databasehelper;

import net.androidla.contentprovider.MyContentProviderMetaData;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SqliteHelper extends SQLiteOpenHelper {
	
	public SqliteHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "create table " + MyContentProviderMetaData.USERS_TABLE_NAME
				+ "(" + MyContentProviderMetaData.UserTableMetaData._ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," 
				+ MyContentProviderMetaData.UserTableMetaData.USER_NAME
				+ " varchar(20));";
		db.execSQL(sql);
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值