Description of ContentProvider database sharing instance

Source: Internet
Author: User
It is not so busy now. We need to take the time to accumulate the knowledge to be summarized. This year, we have re-divided the project team and we should not be so busy in the new project, it seems that you have time to learn something about yourself. Now, what I need is time. As long as you keep working hard, one day you will be different from each other. Come on. 1. Number of contentproviders

It is not so busy now. We need to take the time to accumulate the knowledge to be summarized. This year, we have re-divided the project team and we should not be so busy in the new project, it seems that you have time to learn something about yourself. Now, what I need is time. As long as you keep working hard, one day you will be different from each other. Come on. 1. Number of contentproviders

It is not so busy now. We need to take the time to accumulate the knowledge to be summarized. This year, we have re-divided the project team and we should not be so busy in the new project, it seems that you have time to learn something about yourself. Now, what I need is time. As long as you keep working hard, one day you will be different from each other. Come on.



1. ContentProvider database sharing-Overview
2. ContentProvider database sharing-instance description
3. ContentProvider database sharing-MIME type and getType ()
4. ContentProvider database sharing-read and write permissions and data listening


In the previous article, we have explained the overall process and design method of ContentProvder. In this article, we will introduce the operation process of ContentProvider through examples;

1. ContentProvider provides the database query interface

In the previous article, we mentioned that two applications transmit messages through the Content URI. After receiving the URI, our application completes the corresponding database operation function by matching. A little confused? It doesn't matter. I will explain it in detail below. What I want to talk about here is the database operations to be completed after successful matching !!! Well, our first step is to create a database and a data table.

1. Use SQLiteOpenHelper to create databases and data tables

Here we are in a database ("harvic. create two data tables "first" and "second". Each table has an additional field "table_name" to save the name of the current data table.
The Code is as follows:

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. Create a class PeopleContentProvider using the database operation interface provided by ContentProvider, derived from the ContentProvider base class. After writing the class, query (), insert (), update (), delete () and getType () methods. These Methods Operate Database Interfaces Based on the uploaded URI. The PeopleContentProvider is as follows:
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. Use UriMatcher to match Uris. Let's ignore the specific operations of these functions. First, think about what I mentioned in the previous section. When a URI matches in the ContentProvider class step by step, what will happen? -- use UriMatcher to perform another match !!! After the UriMatcher match is successful, the corresponding operation is performed. Therefore, the above operations are after the UriMatcher match.
Well, let's see how UriMatcher matches.
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;    }    …………}
The above code is the most important sentence:
sUriMatcher.addURI(AUTHORITY, "first", MATCH_FIRST);
The official declaration of addUri is:
public void addURI (String authority, String path, int code)
  • Authority:This parameter is the authority parameter of ContentProvider, which must be the same as the authorities value of the corresponding provider in AndroidManifest. xml;
  • Path:In this example, we construct two Uris.
    (1), content: // com. harvic. provider. PeopleContentProvider/frist
    (2), content: // com. harvic. provider. PeopleContentProvider/second
    The path matches/first or/second after authority.
  • Code:This value is the matching value of the corresponding number returned after matching the path;
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
If the match fails, UriMatcher. NO_MATCH is returned.
We need to make an application: externally, we can use two URIs to send to us, when there is content: // com. harvic. provider. when PeopleContentProvider/frist is enabled, the first database is operated. If content: // com. harvic. provider. operate the second database when PeopleContentProvider/second
4. insert Method

Next, let's take a look at the insert method. The main function is to insert data into the first database when URI matches content: // com. harvic. provider. lelecontentprovider/frist.
When the URI matches content: // com. harvic. provider. PeopleContentProvider/second, insert the data into the second database.

@Overridepublic 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;}
The above code is described as follows:
First, use UriMatcher. match (uri) to match the incoming URI. If the URI matches content: // com. harvic. provider. peopleContentProvider/frist match, 1 is returned, that is, MATCH_FIRST;
That is, when it matches "/first", it inserts the data key-Value Pair (values) into the first table:
long rowID = db.insert(DatabaseHelper.TABLE_FIRST_NAME, null, values);
After insertion, the current row number of the newly inserted record is returned, and the row number is added to the end of the URI as the result.
Uri retUri = ContentUris.withAppendedId(CONTENT_URI_FIRST, rowID);
When Matching content: // com. harvic. provider. PeopleContentProvider/second, we will not repeat it here.
5. update () method

After reading the insert method, the update method is not difficult, but also based on UriMatcher. the return value of match (uri) is used to determine which URI is currently matched, and the corresponding database is operated based on the matched URI. The Code is as follows:

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;}
Call getContentResolver () at the end (). notifyChange (uri, null); to notify the current database of changes, so that all applications listening to this database can perform corresponding operations, and to listen to and respond to shared database variables, we will talk about it in the last article. This is not mentioned here. It is no problem to add this sentence here. I am just an introduction here. You can understand this.
6. query () method

As for the query () method, I will not elaborate on it. Just like above, we can operate different query operations based on different Uris. The Code is as follows:

Public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) {SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder (); switch (sUriMatcher. match (uri) {case MATCH_FIRST: // you can specify the queryBuilder for the queried table. 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); return cursor ;}
7. The delete () method is as follows:
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. The getType () function is not available for the time being. NULL is returned directly. In the next article, we will specifically discuss the function's role and significance.
    public String getType(Uri uri) {        return null;    }
9. Declare provider in AndroidManifest. xml to declare Provider in AndroidManifest. xml:
 
2. Third-party applications share databases through URI operations 1. ContentResolver operations URI

In third-party applications, how do we use URIs to perform operations on the number of shared data? This is done using the ContentResolver class.
The method for obtaining the ContentResolver instance is:

ContentResolver cr = this.getContentResolver();
ContentResolver has the following database operations: Query, insert, update, and delete.
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)
The first parameter is the URI to be specified, and then the following parameters specify the database condition -- where statement and corresponding parameters; next we will take a user instance to see how these functions are actually used.
2. Global Operations

Create a new project named "UseProvider". The interface looks like this:


There are two buttons at the top to switch which URI is used to add, delete, modify, and query operations. Because different Uris operate on different data tables, we use different Uris, operations are performed on different data tables;
First, list the two URIs to be matched and the globally used URI (mCurrentURI). The mCurrentURI is the URI corresponding to/first by default. If you want to switch, use the top two buttons on the interface to switch the URI currently in use.

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 () -- query operations:
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();}
In fact, the query operation is completed with only one sentence: (because no limit statement is added, all records in this data table are queried)
Cursor cursor = this.getContentResolver().query(mCurrentURI, null, null, null, null);
Then, the Returned Database record pointer Cursor is read to read all records one by one;
4. insert () insert operation
public final Uri insert (Uri url, ContentValues values)
The insert operation is a bit special. The second function requires that the key-value pair of the ContentValues to be inserted be passed in. In fact, it is not difficult, just like a common database operation;
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 () update operations
public final int update (Uri uri, ContentValues values, String where, String[] selectionArgs)
This function means to first use the where statement to find the record to be updated, and then update the values key-value pair to the corresponding record;
  • Uri: The URI to be matched.
  • Values: the key-value pair to be updated.
  • Where: The corresponding where statement in SQL
  • SelectionArgs: If a variable parameter exists in the where statement, it can be placed in the selectionArgs string array. These are used in the same way as those in the database.
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();}
Here, we update the detail character of the record with _ id = 1 and add N exclamation points to the end.
6. delete () delete operation
public final int delete (Uri url, String where, String[] selectionArgs)
The parameters of the delete operation are easy to understand. The second parameter is the filter condition of the where statement in SQL. selectionArgs is also a variable parameter in the Where statement;
private void delete() {    int count = this.getContentResolver().delete(mCurrentURI, "_id = 1", null);    Log.e("test ", "count=" + count);    query();}
Delete records with _ id = 1;
Iii. Results

1. Run the APP ContentProvider: ContentProviderBlog, and then run UseProvider;
2. Use content: // com. harvic. provider. PeopleContentProvider/frist to operate the ContentProviderBlog database:
3. Click two insert operations to view the returned URI. After each URI, the row number of the new inserted record is added.


4. Perform the query operation-query ()
Because our URI is for the first record, table_name here can be seen as "first", that is, we operate on the first table, if we change the URI to the URI corresponding to second, the operation will be changed to the second table.


5. update operations-update ()

Execute the Update () operation, the detail field of the _ id = 1 record will be updated to "my name is harvic !!!!!!!!!!!!!!!!!!!!!! !!!! "; The values of other records remain unchanged. The results are as follows:


6. delete operation -- delete ()

Similarly, the delete operation only deletes records with _ id = 1. Therefore, the query () result after the operation is as follows:


Summary:In this article, we wrote two applications: ContentProviderBlog and UseProvider. ContentProviderBlog is derived from ContentProvider and provides interfaces for third-party operations on its database. UseProvider is a so-called third-party application, use URI in UseProvider to operate the database of ContentProviderBlog;

Now, the entire article is over. After reading this article, let's look back at the first article. We should have a clear understanding of the overall process of database sharing between applications.


The source code comes. The Source Code contains two parts:

1. ContentProviderBlog: This is an APP that provides shared database interfaces;
2. UseProvider: A third party uses URI to operate the database APP;


If this article helps you, remember to pay attention to it.

Source code: http://download.csdn.net/detail/harvic880925/8528507

Http://blog.csdn.net/harvic880925/article/details/44591631 thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.