ContentProvider实例
来源:互联网 发布:淘宝宝贝排名软件 编辑:程序博客网 时间:2024/05/22 07:53
************************************项目一**************************************
在配置文件中
<provider android:name=".PeopleContentProvider" android:authorities="com.harvic.provider.PeopleContentProvider" android:exported="true" />
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.harvic.contentproviderblog.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /></RelativeLayout>
package com.harvic.contentproviderblog;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}
DatabaseHelper
package com.harvic.contentproviderblog;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.provider.BaseColumns;import android.util.Log;/** * 利用SQLiteOpenHelper创建数据库、数据表 * */public class DatabaseHelper extends SQLiteOpenHelper {//数据库名字public static final String DATABASE_NAME = "harvic.db";//版本号码public static final int DATABASE_VERSION = 1;//数据库文件1、2public static final String TABLE_FIRST_NAME = "first";public static final String TABLE_SECOND_NAME = "second";//创建数据文件1sql语句public static final String SQL_CREATE_TABLE_FIRST = "CREATE TABLE "+ TABLE_FIRST_NAME + "(" + BaseColumns._ID+ " INTEGER PRIMARY KEY AUTOINCREMENT," + "table_name"+ " VARCHAR(50) default 'first'," + "name" + " VARCHAR(50),"+ "detail" + " TEXT" + ");";//创建数据库文件2sql语句public static final String SQL_CREATE_TABLE_SECOND = "CREATE TABLE "+ TABLE_SECOND_NAME + " (" + BaseColumns._ID+ " INTEGER PRIMARY KEY AUTOINCREMENT," + "table_name"+ " VARCHAR(50) default 'second'," + "name" + " VARCHAR(50),"+ "detail" + " TEXT" + ");";/** * public SQLiteOpenHelper(Context context, String name, CursorFactory * factory, int version) { this(context, name, factory, version, null); } * 调用父类的构造方法,初始化DATABASE_NAME数据库名字 */public DatabaseHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);} /** * 第一次链接数据库,如果数据库文件未创建,系统自动创建数据库文件, * onCreate方法就会自动调用,并且只调用一次 */ @Overridepublic void onCreate(SQLiteDatabase db) {Log.e("harvic", "create table: " + SQL_CREATE_TABLE_FIRST);db.execSQL(SQL_CREATE_TABLE_FIRST);db.execSQL(SQL_CREATE_TABLE_SECOND);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {db.execSQL("DROP TABLE IF EXISTS first");db.execSQL("DROP TABLE IF EXISTS second");onCreate(db);}}
PeopleContentProvider
package com.harvic.contentproviderblog;import android.content.ContentProvider;import android.content.ContentUris;import android.content.ContentValues;import android.content.UriMatcher;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteQueryBuilder;import android.net.Uri;/** * 利用ContentProvider提供数据库操作接口 * */public class PeopleContentProvider extends ContentProvider {// 创简Url匹配器private static final UriMatcher sUriMatcher;private static final int MATCH_FIRST = 1;private static final int MATCH_SECOND = 2;/** * 对外暴露2个url地址 // 注册ContentProvider的authorities */public static final String AUTHORITY = "com.harvic.provider.PeopleContentProvider";public static final Uri CONTENT_URI_FIRST = Uri.parse("content://"+ AUTHORITY + "/frist");public static final Uri CONTENT_URI_SECOND = Uri.parse("content://"+ AUTHORITY + "/second");/** * 当一个URI逐级匹配到了ContentProvider类里以后,会怎么做——利用UriMatcher进行再次匹配!!! * UriMatcher匹配成功以后,才会执行对应的操作。所以下面的那些操作是在UriMatcher匹配之后。 * * addURI(String authority, String path, int code)3个参数 * * path:就匹配在URI中authority后的那一坨,在这个例子中,我们构造了两个URI * (1)、content://com.harvic.provider.PeopleContentProvider/frist * (2)、content://com.harvic.provider.PeopleContentProvider/second * 而path匹配的就是authority后面的/first或者/second */static {sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);sUriMatcher.addURI(AUTHORITY, "first", MATCH_FIRST);sUriMatcher.addURI(AUTHORITY, "second", MATCH_SECOND);}/** * 创建DatabaseHelper实例对象 */private DatabaseHelper mDbHelper;@Overridepublic boolean onCreate() {mDbHelper = new DatabaseHelper(getContext());return false;}/** * 当URI要获取列表集的时候,把全部结果返回 如果URI是要获取单个ITEM,则将单个ITEM的信息返回 */@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {//是一个构造SQL查询语句的辅助类。SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();switch (sUriMatcher.match(uri)) {case MATCH_FIRST:// 设置查询的表queryBuilder.setTables(DatabaseHelper.TABLE_FIRST_NAME);break;case MATCH_SECOND:queryBuilder.setTables(DatabaseHelper.TABLE_SECOND_NAME);break;default:throw new IllegalArgumentException("Unknow URI: " + uri);}SQLiteDatabase db = mDbHelper.getReadableDatabase();//查询某个表Cursor cursor = queryBuilder.query(db, projection, selection,selectionArgs, null, null, null);return cursor;}@Overridepublic String getType(Uri uri) {return null;}/** * 首先,利用UriMatcher.match(uri)来匹配到来的URI,如果这个URI与content://com.harvic.provider * .PeopleContentProvider/frist匹配,就会返回1即MATCH_FIRST; * 即:当与"/first"匹配时,就将数据键值对(values)插入到first表中: long rowID = * db.insert(DatabaseHelper.TABLE_FIRST_NAME, null, values); * 插入之后,会返回新插入记录的当前所在行号,然后将行号添加到URI的末尾,做为结果返回 Uri retUri = * ContentUris.withAppendedId(CONTENT_URI_FIRST, rowID); * 当匹配content://com.harvic.provider.PeopleContentProvider/second时,同理,不再赘述。 */@Overridepublic Uri insert(Uri uri, ContentValues values) {SQLiteDatabase db = mDbHelper.getWritableDatabase();switch (sUriMatcher.match(uri)) {case MATCH_FIRST: {// insert(String table, String nullColumnHack, ContentValues values)long rowID = db.insert(DatabaseHelper.TABLE_FIRST_NAME, null,values);if (rowID > 0) {Uri retUri = ContentUris.withAppendedId(CONTENT_URI_FIRST,rowID);return retUri;}}break;case MATCH_SECOND: {long rowID = db.insert(DatabaseHelper.TABLE_SECOND_NAME, null,values);if (rowID > 0) {Uri retUri = ContentUris.withAppendedId(CONTENT_URI_SECOND,rowID);return retUri;}}break;default:throw new IllegalArgumentException("Unknown URI " + uri);}return null;}@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {SQLiteDatabase db = mDbHelper.getWritableDatabase();int count = 0;switch (sUriMatcher.match(uri)) {case MATCH_FIRST:count = db.delete(DatabaseHelper.TABLE_FIRST_NAME, selection,selectionArgs);break;case MATCH_SECOND:count = db.delete(DatabaseHelper.TABLE_SECOND_NAME, selection,selectionArgs);break;default:throw new IllegalArgumentException("Unknow URI :" + uri);}this.getContext().getContentResolver().notifyChange(uri, null);return count;}/** * 在最后调用getContentResolver().notifyChange(uri, * null);来通知当前的数据库有改变,让监听这个数据库的所有应用执行对应的操作,有关共享数据库的变量监听与响应的问题, */@Overridepublic int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {SQLiteDatabase db = mDbHelper.getWritableDatabase();int count = 0;switch (sUriMatcher.match(uri)) {case MATCH_FIRST:count = db.update(DatabaseHelper.TABLE_FIRST_NAME, values,selection, selectionArgs);break;case MATCH_SECOND:count = db.update(DatabaseHelper.TABLE_SECOND_NAME, values,selection, selectionArgs);break;default:throw new IllegalArgumentException("Unknow URI : " + uri);}this.getContext().getContentResolver().notifyChange(uri, null);return count;}}
******************************项目二**********************************
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/first_uri" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="使用CONTENT_URI_FIRST"/> <Button android:id="@+id/second_uri" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="使用CONTENT_URI_SECOND"/> </LinearLayout> <Button android:id="@+id/insert" android:text="insert" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/query" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="query"/> <Button android:id="@+id/delete" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="delete"/> <Button android:id="@+id/update" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="update"/></LinearLayout>
MainActivity
package com.harvic.useprovider; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler;import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements View.OnClickListener { private Button btnQuery, btnDelete, btnInsert, btnUpdate, btnUseFirstURI, btnUseSecondURI; private TextView mtv; // 定义ContentProvider字段名 public static final String AUTHORITY = "com.harvic.provider.PeopleContentProvider"; // 创建2个url进行 public static final Uri CONTENT_URI_FIRST = Uri.parse("content://" + AUTHORITY + "/first"); public static final Uri CONTENT_URI_SECOND = Uri.parse("content://" + AUTHORITY + "/second"); public static Uri mCurrentURI = CONTENT_URI_FIRST; //获取实例 private DataBaseObserver observer; @Override protected void onDestroy() { super.onDestroy(); //取消监听 getContentResolver().unregisterContentObserver(observer); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //创建对象 observer = new DataBaseObserver(new Handler()); //注册指定URI 变动监听 getContentResolver().registerContentObserver(CONTENT_URI_FIRST,true,observer); btnDelete = (Button) findViewById(R.id.delete); btnInsert = (Button) findViewById(R.id.insert); btnQuery = (Button) findViewById(R.id.query); btnUpdate = (Button) findViewById(R.id.update); btnUseFirstURI = (Button) findViewById(R.id.first_uri); btnUseSecondURI = (Button) findViewById(R.id.second_uri); mtv = (TextView) findViewById(R.id.tv); mtv.setText("当前URI:" + mCurrentURI.toString()); btnDelete.setOnClickListener(this); btnInsert.setOnClickListener(this); btnQuery.setOnClickListener(this); btnUpdate.setOnClickListener(this); btnUseFirstURI.setOnClickListener(this); btnUseSecondURI.setOnClickListener(this); } /** * 在第三方应用中,我们要如何利用URI来执行共享数据数的操作呢,这是利用ContentResolver这个类来完成的!!!!!!!!!!!!! * 获取ContentResolver实例的方法为: * * ContentResolver cr = this.getContentResolver(); */ private void insert() { ContentValues values = new ContentValues(); values.put("name", "hello"); values.put("detail", "my name is harvic"); Uri uri = this.getContentResolver().insert(mCurrentURI, values); Log.e("test ", uri.toString()); } private void query() { Cursor cursor = this.getContentResolver().query(mCurrentURI, null, null, null, null); Log.e("test ", "count=" + cursor.getCount()); cursor.moveToFirst(); while (!cursor.isAfterLast()) { String table = cursor .getString(cursor.getColumnIndex("table_name")); String name = cursor.getString(cursor.getColumnIndex("name")); String detail = cursor.getString(cursor.getColumnIndex("detail")); Log.e("test", "table_name:" + table); Log.e("test ", "name: " + name); Log.e("test ", "detail: " + detail); cursor.moveToNext(); } cursor.close(); } private void update() { ContentValues values = new ContentValues(); values.put("detail", "my name is harvic !!!!!!!!!!!!!!!!!!!!!!!!!!"); int count = this.getContentResolver().update(mCurrentURI, values, "_id = 1", null); Log.e("test ", "count=" + count); query(); } private void delete() { int count = this.getContentResolver().delete(mCurrentURI, "_id = 1", null); Log.e("test ", "count=" + count); query(); } private void switchURI(Uri uri) { mCurrentURI = uri; mtv.setText("当前URI:" + mCurrentURI.toString()); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.first_uri: { switchURI(CONTENT_URI_FIRST); } break; case R.id.second_uri: { switchURI(CONTENT_URI_SECOND); } break; case R.id.delete: { delete(); } break; case R.id.insert: { insert(); } break; case R.id.query: { query(); } break; case R.id.update: { update(); } break; default: break; } } }
DataBaseObserver
package com.harvic.useprovider;import android.database.ContentObserver;import android.os.Handler;import android.util.Log;public class DataBaseObserver extends ContentObserver { public DataBaseObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Log.d("harvic","received first database changed"); }}
0 0
- ContentProvider实例
- ContentProvider实例
- ContentProvider 实例
- ContentProvider实例
- ContentProvider实例
- MyNotes(ContentProvider实例)
- 自定义ContentProvider 实例演示
- ContentProvider原理及实例
- contentprovider讲解+实例
- (Android) ContentProvider 实例
- 操纵系统ContentProvider实例
- ContentProvider与ContentResolver实例
- ContentProvider实例整理
- android ContentProvider 使用实例
- ContentProvider原理及实例 .
- ContentProvider原理及实例
- ContentProvider原理及实例
- Android ContentProvider实例
- Asp.net动态页面静态化之include和parse区别
- 排序算法_C++(一)插入排序之直接插入排序
- 栈和堆的区别
- 津津的储蓄计划
- c++ primer plus 第七章-编程题7.13.5《求任意一个数的阶乘》
- ContentProvider实例
- HDU 2563 统计问题 (递推)
- Android 4.0.x 浏览器不触发 ontouchend 事件的bug
- 嵌入式软件开发概述(4.1)------嵌入式软件程序设计
- HDU 1232 畅通工程
- hdu 3065 AC自动机 匹配串编号以及出现次数
- 一切开始,无论怎样,希望自己坚持下去
- String字符串方法详解
- HOWTO django + celery + rabbitmq simple setup for testing purpose