First, the concept of ContentProvider
ContentProvider: Provides a unified interface for storing and retrieving data. You can share data between different applications. Android has provided default contentprovider for some of the most common data
1, ContentProvider Use the form of table to organize data
Regardless of the source of the data, ContentProvider will think of it as a table, then organize the data into tables
2, the method provided by ContentProvider
Query: Querying
Insert: Inserting
Update: Updates
Delete: Remove
GetType: Get Data type
OnCreate: callback function to invoke when creating data
3, each contentprovider has a public URI, which is used to represent the data provided by this contentprovider. The ContentProvider provided by Android are stored in the Android.provider package.
Second, the internal principle of ContentProvider
Customizing a contentprovider to implement the internal principle
Steps:
1. Define a Content_uri constant (the string inside must be unique)
public static final Uri Content_uri = Uri.parse ("content://com. Wangweida.mycontentprovider ");
If there is a child table, the URI is:
public static final Uri Content_uri = Uri.parse ("content://com. Wangweida.mycontentprovider/users ");
2, define a class, Inherit ContentProvider
public class Mycontentprovider extends ContentProvider
3. Implement all ContentProvider methods (query, insert, UPDATE, delete, GetType, onCreate)
Package com. WANGWEIDA.CP;
Import Java.util.HashMap;
Import com. WangWeiDa.cp.MyContentProviderMetaData.UserTableMetaData;
Import com. WangWeiDa.data.DatabaseHelp;
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;
Import Android.text.TextUtils;
public class Mycontentprovider extends ContentProvider {
Access all columns of a table
public static final int incoming_user_collection = 1;
Access a separate column
public static final int incoming_user_single = 2;
Class for manipulating URIs
public static final Urimatcher Urimatcher;
Add a custom URI for Urimatcher
static{
Urimatcher = new Urimatcher (urimatcher.no_match);
Urimatcher.adduri (mycontentprovidermetadata.authorities, "/user",
Incoming_user_collection);
Urimatcher.adduri (mycontentprovidermetadata.authorities, "/user/#",
Incoming_user_single);
}
Private Databasehelp DH;
Alias a database table field
public static HashMap Userprojectionmap;
Static
{
Userprojectionmap = new HashMap ();
Userprojectionmap.put (usertablemetadata._id,usertablemetadata._id);
Userprojectionmap.put (Usertablemetadata.user_name, usertablemetadata.user_name);
}
/**
* Delete table data
*/
@Override
public int Delete (URI Uri, String selection, string[] Selectionargs) {
System.out.println ("delete");
Get a writable database
Sqlitedatabase db = Dh.getwritabledatabase ();
The number of rows to delete and get deleted
int count = Db.delete (Usertablemetadata.table_name, Selection, Selectionargs);
return count;
}
/**
* Database access type
*/
@Override
Public String GetType (Uri uri) {
System.out.println ("GetType");
Based on user request, get data type
Switch (Urimatcher.match (URI)) {
Case Incoming_user_collection:
return MyContentProviderMetaData.UserTableMetaData.CONTENT_TYPE;
Case Incoming_user_single:
return MyContentProviderMetaData.UserTableMetaData.CONTENT_TYPE_ITEM;
Default
throw new IllegalArgumentException ("UnKnown URI" +uri);
}
}
/**
* Insert Data
*/
@Override
Public URI insert (URI uri, contentvalues values) {
Get a writable database
Sqlitedatabase db = Dh.getwritabledatabase ();
Inserts data into the specified table to get the returned ID
Long rowId = Db.insert (usertablemetadata.table_name, null, values);
if (RowId > 0) {//To determine if the insert was executed successfully
If added successfully, take advantage of the newly added ID and
Uri Inserteduseruri = Contenturis.withappendedid (Usertablemetadata.content_uri, rowId);
Notifies the listener that the data has changed
GetContext (). Getcontentresolver (). Notifychange (Inserteduseruri, NULL);
return Inserteduseruri;
}
return URI;
}
/**
* Callback function to invoke when creating ContentProvider
*/
@Override
public Boolean onCreate () {
System.out.println ("OnCreate");
Get the database Help class
DH = new Databasehelp (GetContext (), mycontentprovidermetadata.database_name);
return false;
}
/**
* Query Database
*/
@Override
Public Cursor query (URI uri, string[] projection, String selection,
String[] Selectionargs, String sortOrder) {
Create a SQLite that executes a query
Sqlitequerybuilder QB = new Sqlitequerybuilder ();
Determine user requests, query all or individual
Switch (Urimatcher.match (URI)) {
Case Incoming_user_collection:
Set the name of the table to query
Qb.settables (Usertablemetadata.table_name);
Set the alias for a table field
Qb.setprojectionmap (USERPROJECTIONMAP);
Break
Case Incoming_user_single:
Qb.settables (Usertablemetadata.table_name);
Qb.setprojectionmap (USERPROJECTIONMAP);
Append condition, getpathsegments () gets an array of URI addresses intercepted by the user request, get (1) gets rid of the second element in the address/later
Qb.appendwhere (usertablemetadata._id + "=" + uri.getpathsegments (). Get (1));
Break
}
Set sort
String by;
if (Textutils.isempty (SortOrder)) {
= Usertablemetadata.default_sort_order;
}
else{
= SortOrder;
}
Get a readable database
Sqlitedatabase db = Dh.getreadabledatabase ();
Execute the query, pass in the input
Cursor C = qb.query (db, Projection, selection, Selectionargs, NULL, NULL, as-is);
Setting up Monitoring
C.setnotificationuri (GetContext (). Getcontentresolver (), URI);
return C;
}
/**
* Update Database
*/
@Override
public int update (URI uri, contentvalues values, String selection,
String[] Selectionargs) {
SYSTEM.OUT.PRINTLN ("Update");
Get a writable database
Sqlitedatabase db = Dh.getwritabledatabase ();
Execute UPDATE statement to get updated number of bars
int count = Db.update (Usertablemetadata.table_name, values, selection, Selectionargs);
return count;
}
}
4. Make a statement in Androidminifest.xml
Android:name= ". CP. Mycontentprovider "
Android:authorities= "com. WangWeiDa.cp.MyContentProvider "
/>
* * Provides a constant class for ContentProvider Mycontentprovidermetadata.java
Package com. WANGWEIDA.CP;
Import Android.net.Uri;
Import Android.provider.BaseColumns;
public class Mycontentprovidermetadata {
Uri, where the string must be consistent with the declared authorities
public static final String authorities = "Com.wangweida.cp.MyContentProvider";
Database name
public static final String database_name = "MYCONTENTPROVIDER.DB";
Version of the database
public static final int database_version = 1;
Table name
public static final String users_table_name = "user";
public static final class Usertablemetadata implements basecolumns{
Table name
public static final String table_name = "user";
Access the URI of the ContentProvider
public static final Uri Content_uri = Uri.parse ("content://" + authorities + "/user");
The definition of the data type returned by the ContentProvider
public static final String Content_Type = "Vnd.android.cursor.dir/vnd.myprovider.user";
public static final String Content_type_item = "Vnd.android.cursor.item/vnd.myprovider.user";
Column Name
public static final String user_name = "NAME";
The default sorting method
public static final String Default_sort_order = "_id desc";
}
}
Introduction to Android ContentProvider