ContentProvider数据库共享之实例讲解
前言:现在这段时间没这么忙了,要抓紧时间把要总结的知识沉淀下来,今年重新分了项目组,在新项目中应该不会那么忙了,看来有时间来学一些自己的东西了。现在而言,我需要的是时间。只要不断的努力,总有一天,你会与从不同。加油。 1、《ContentProvider数
前言:现在这段时间没这么忙了,要抓紧时间把要总结的知识沉淀下来,今年重新分了项目组,在新项目中应该不会那么忙了,看来有时间来学一些自己的东西了。现在而言,我需要的是时间。只要不断的努力,总有一天,你会与从不同。加油。
1、《ContentProvider数据库共享之——概述》
2、《ContentProvider数据库共享之——实例讲解》
3、《ContentProvider数据库共享之——MIME类型与getType()》
4、《ContentProvider数据库共享之——读写权限与数据监听》
在上篇文章中,已经给大家初步讲解了有关ContentProvder的整体流程及设计方式,在这篇文章中将通过实例来讲述ContentProvider的操作过程;
一、ContentProvider提供数据库查询接口
在上篇中,我们提到过,两个应用间是通过Content URI来媒介传递消息的,我们的应用在收到URI以后,通过匹配完成对应的数据库操作功能。听的有点迷糊?没关系,下面会细讲,我这里要说的是,匹配成功后要完成的数据库操作!!!那好,我们的第一步:建数据库,数据表
1、利用SQLiteOpenHelper创建数据库、数据表
在这里,我们在一个数据库(“harvic.db”)中创建两个数据表”first”与”second”;每个表都有多出一个字段“table_name”,来保存当前数据表的名称
代码如下:
public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "harvic.db"; public static final int DATABASE_VERSION = 1; public static final String TABLE_FIRST_NAME = "first"; public static final String TABLE_SECOND_NAME = "second"; 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" + ");" ; 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 DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public 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); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS first"); db.execSQL("DROP TABLE IF EXISTS second"); onCreate(db); } }
2、利用ContentProvider提供数据库操作接口
新建一个类PeopleContentProvider,派生自ContentProvider基类,写好之后,就会自动生成query(),insert(),update(),delete()和getType()方法;这些方法就是根据传过来的URI来操作数据库的接口。此时的PeopleContentProvider是这样的:public class PeopleContentProvider extends ContentProvider { @Override public boolean onCreate() { return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } }
3、使用UriMatcher匹配URI
我们先不管这几个函数的具体操作,先想想在上节中我提到的当一个URI逐级匹配到了ContentProvider类里以后,会怎么做——利用UriMatcher进行再次匹配!!!UriMatcher匹配成功以后,才会执行对应的操作。所以上面的那些操作是在UriMatcher匹配之后。好,我们就先看看UriMatcher是怎么匹配的。
public class PeopleContentProvider extends ContentProvider { private static final UriMatcher sUriMatcher; private static final int MATCH_FIRST = 1; private static final int MATCH_SECOND = 2; 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"); static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(AUTHORITY, "first", MATCH_FIRST); sUriMatcher.addURI(AUTHORITY, "second", MATCH_SECOND); } private DatabaseHelper mDbHelper; @Override public boolean onCreate() { mDbHelper = new DatabaseHelper(getContext()); return false; } ………… }
sUriMatcher.addURI(AUTHORITY, "first", MATCH_FIRST);
public void addURI (String authority, String path, int code)
- authority:这个参数就是ContentProvider的authority参数,这个参数必须与AndroidManifest.xml中的对应provider的authorities值一样;
-
path:就匹配在URI中authority后的那一坨,在这个例子中,我们构造了两个URI
(1)、content://com.harvic.provider.PeopleContentProvider/frist
(2)、content://com.harvic.provider.PeopleContentProvider/second
而path匹配的就是authority后面的/first或者/second - code:这个值就是在匹配path后,返回的对应的数字匹配值;
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
我们要做一个应用:外部可以使用两个URI传来给我们,当传来content://com.harvic.provider.PeopleContentProvider/frist时,就操作first数据库;如果传来content://com.harvic.provider.PeopleContentProvider/second时,就操作second数据库
4、insert方法
下面先看看insert方法,主要功能为:当URI匹配content://com.harvic.provider.PeopleContentProvider/frist时,将数据插入first数据库
当URI匹配content://com.harvic.provider.PeopleContentProvider/second时,将数据插入second数据库
@Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); switch (sUriMatcher.match(uri)){ case MATCH_FIRST:{ 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; }
首先,利用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 retUri = ContentUris.withAppendedId(CONTENT_URI_FIRST, rowID);
5、update()方法
在看了insert方法之后,update方法难度也不大,也是根据UriMatcher.match(uri)的返回值来判断当前与哪个URI匹配,根据匹配的URI来操作对应的数据库,代码如下:
public 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; }
6、query() 方法
至于query()方法就不再细讲了,跟上面的一样,根据不同的URI来操作不同的查询操作而已,代码如下:
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { 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; }
7、delete()方法
delete()方法如下:public 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); } return count; }
8、getType()
这个函数,我们这里暂时用不到,直接返回NULL,下篇我们会专门来讲这个函数的作用与意义。public String getType(Uri uri) { return null; }
9、AndroidManifest.xml中声明provider
在AndroidManifest.xml中要声明我们创建的Provider:<provider android:authorities="com.harvic.provider.PeopleContentProvider" android:name=".PeopleContentProvider" android:exported="true"></provider>
二、第三方应用通过URI操作共享数据库
1、ContentResolver操作URI
在第三方应用中,我们要如何利用URI来执行共享数据数的操作呢,这是利用ContentResolver这个类来完成的。
获取ContentResolver实例的方法为:
ContentResolver cr = this.getContentResolver();
public final Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) public final Uri insert (Uri url, ContentValues values) public final int update (Uri uri, ContentValues values, String where, String[] selectionArgs) public final int delete (Uri url, String where, String[] selectionArgs)
2、全局操作
新建一个工程,命名为“UseProvider”,界面长这个样子:
最上头有两个按钮,用来切换当前使用哪个URI来增、删、改、查操作;由于不同的URI会操作不同的数据表,所以我们使用不同的URI,会在不同的数据表中操作;
先列出来那两个要匹配的URI,以及全局当前要使用的URI(mCurrentURI ),mCurrentURI 默认是/first对应的URI,如果要切换,使用界面上最上头的那两个按钮来切换当前所使用的URI。
public static final String AUTHORITY = "com.harvic.provider.PeopleContentProvider"; 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;
3、query()——查询操作
下面先来看看查询操作的过程: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(); }
Cursor cursor = this.getContentResolver().query(mCurrentURI, null, null, null, null);
4、insert()插入操作
public final Uri insert (Uri url, ContentValues values)
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()); }
5、update()更新操作
public final int update (Uri uri, ContentValues values, String where, String[] selectionArgs)
- uri:即要匹配的URI
- values:这是要更新的键值对
- where:SQL中对应的where语句
- selectionArgs:where语句中如果有可变参数,可以放在selectionArgs这个字符串数组中;这些与数据库中的用法一样,不再细讲。
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(); }
6、delete()删除操作
public final int delete (Uri url, String where, String[] selectionArgs)
private void delete() { int count = this.getContentResolver().delete(mCurrentURI, "_id = 1", null); Log.e("test ", "count=" + count); query(); }
三、结果
1、我们先运行ContentProvider对应的APP:ContentProviderBlog,然后再运行UseProvider;
2、然后先用content://com.harvic.provider.PeopleContentProvider/frist 来操作ContentProviderBlog的数据库:
3、点两个insert操作,看返回的URI,在每个URI后都添加上了当前新插入记录的行号
4、然后做下查询操作——query()
由于我们的URI是针对first记录的,所以在这里的table_name,可以看到是“first”,即我们操作的是first表,如果我们把URI改成second对应的URI,那操作的就会变成second表
5、更新操作——update()
执行Update()操作,会将_id = 1的记录的detail字段更新为“my name is harvic !!!!!!!!!!!!!!!!!!!!!!!!!!”;其它记录的值不变,结果如下:
6、删除操作——delete()
同样,删除操作也会只删除_id = 1的记录,所以操作之后的query()结果如下:
总结:在这篇文章中,我们写了两个应用ContentProviderBlog和UseProvider,其中ContentProviderBlog派生自ContentProvider,提供第三方操作它数据库的接口;而UseProvider就是所谓第三方应用,在UseProvider中通过URI来操作ContentProviderBlog的数据库;
好了,到这里,整个文章就结束了,大家在看完这篇文章以后再回过头来看第一篇,应该对应用间数据库共享的整体流程已经有清晰的了解了。
源码来了,源码包含两部分内容:
1、《ContentProviderBlog》:这个是提供共享数据库接口的APP;
2、《UseProvider》:第三方通过URI来操作数据库的APP;
如果本文有帮到你,记得关注哦
源码下载地址:http://download.csdn.net/detail/harvic880925/8528507
http://blog.csdn.net/harvic880925/article/details/44591631 谢谢!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

PHP is a back-end programming language widely used in website development. It has powerful database operation functions and is often used to interact with databases such as MySQL. However, due to the complexity of Chinese character encoding, problems often arise when dealing with Chinese garbled characters in the database. This article will introduce the skills and practices of PHP in handling Chinese garbled characters in databases, including common causes of garbled characters, solutions and specific code examples. Common reasons for garbled characters are incorrect database character set settings: the correct character set needs to be selected when creating the database, such as utf8 or u

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.
