ContentProvider: content Provider
1. Provides a unified interface for storing and reading data
2, using ContentProvider, the application can realize data sharing
3, many of the data built into Android are used in the form of ContentProvider for developers to call (such as video, audio, images, contacts, etc.)
4. When an application inherits the ContentProvider class and overrides the method used to provide data and store data, it can share its data with other applications.
Let's take a look at the Uri:
Uri, which is the Universal Resource Identifier
1, the URI represents the data to be manipulated, each kind of resources available on Android-images, video clips, etc. can be represented by a URI
2, the URI generally consists of three parts: access to the resource naming mechanism; the host name of the resource, the name of the resource itself, represented by the path.
The URI of Android consists of the following three parts: "content://" + Data path + ID (optional),
such as: Uri:content://contacts/people of all contact persons
A contact's URI:CONTENT://CONTACTS/PEOPLE/5//contact with ID 5
3. If you want to convert a string to a URI, you can use the parse () method in the URI class as follows:
Uri uri = uri.parse ("Content://com.archer.contentprovider")
Contentresolver:
In Android, each application is able to share data, and for each application program has a ContentProvider instance to store,
Contentresolver is a ContentProvider instance for managing all programs, and the data can be added, deleted, modified, and queried by Contentrescolver.
Get an instance by Getcontentrescolver ()
Below by creating a content Provider and using the Sqllite database for data sharing
First, define the Content_uri of the ContentProvider and be the class variable of the public static final URI type
A unique string value must be set for it, typically named with the full name of the class
Package com. Contentproviderdemo.archer;import Android.net.uri;import Android.provider.basecolumns;public class MyUsers {public Static final String authority = "Com.archer.ContentProvider"; _id field is already included in//basecolumn class public static final class User Impl Ements basecolumns{public static final Uri Content_uri =uri.parse ("Content://com.archer.contentprovider");// Table data column public static final String user_name = "user_name";}}
Then create a class to inherit ContentProvider
Package com. Contentproviderdemo.archer;import android.content.contentprovider;import android.content.contenturis ;import android.content.contentvalues;import android.content.context;import android.database.cursor;import android.database.sqlexception;import android.database.sqlite.sqlitedatabase;import android.database.sqlite.sqliteopenhelper;import android.database.sqlite.sqlitequerybuilder;import android.net.uri;public class mycontentprovider extends contentprovider{/** * define a Sqlitedatabase variable * Android provides a class named Sqlitedatabase that encapsulates some of the APIs that manipulate the database. * uses it to implement basic CRUD (insert, query, UPDATE, DELETE) operations, and can obtain a DB instance through Getwritabledatabase () and getreadabledatabase () */ private sqlitedatabase sqldb;private databasehelper dbhelper;private static final string database_name = "users.db"; //database name private static final int database_version = 1; //database Version//table name private static final string table_name = "User";//Table name/** * First you need to create a database (define an inner class, inherit the Sqliteopenhelper class, override its methods) * sqliteopenhelper is an abstract class that manages the creation and versioning of databases. * to use it must implement its oncreate (Sqlitedatabase), Onupgrade (Sqlitedatabase, int, int) method * oncreate: Executed when the database was first built, such as creating tables, initializing data, and so on. * onupgrade: Executes when the database needs to be updated, such as deleting the old table and creating a new table. * @author administrator */private static class databasehelper extends SQLiteOpenHelper{/*** How to create a database * name the name of the database * factory the cursor factory of the query database in general, with the SDK default * version database version is generally larger than 0*/public databasehelper (Context context) {super (Context,database_name, null,database_version);} @Overridepublic void oncreate (sqlitedatabase db) {String sq1 = "Create table " + TABLE_NAME + "( _id integer primary key autoincrement, user_name text); "; //The SQL statement db.execsql (SQ1) that created the table, //the method to invoke when creating the table}/*** Update data, such as adding tables, modifying data/@Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//adds a column of Db.execsql (" Drop table if exists " + table_name); onCreate (db);}} @Overridepublic int delete (URI URI, STRING S, STRING[] ARG2) {return 0;} @Overridepublic string gettype (uri arg0) {return null;} /** * inserting data The * contentvalues class is responsible for storing some name-value pairs, the name of which is a string type, and the value is the base type. */@Overridepublic uri insert (uri uri, contentvalues contentvalues) {// Open the database in read-write mode, once the database disk space is full, the database can only read and not write, will open the failure sqldb = dbhelper.getwritabledatabase (); //insert a new record, If the insert succeeds, the ID of this record is returned, and if the insert fails it returns -1long rowid = sqldb.insert (table_name, "", contentvalues) ; if (rowId > 0) { // contenturis class is used to get the ID part of the URI path //appendid: Add Iduri rowuri to the URI = contenturis.appendid (MyUsers.User.CONTENT_URI.buildUpon (), rowid). Build (); // Getcontextresolver (). Notifychange (): Gets a Contextresolver object and updates the contents inside. GetContext (). Getcontentresolver (). Notifychange (rowuri, null); Return rowuri;} Throw new sqlexception ("Fail to insert row into" +uri); /** * This is a callback function that is called when generating an object of the same class, creating a database */@Overridepublic boolean oncreate () { Dbhelper = new databasehelper (GetContext ());return (dbhelper == null) ? false:true;} /** * Query */@Overridepublic cursor query (uri uri, string[] projection, string selection, string[] selectionargs,string sortorder) {// sqlitequerybuilder is an auxiliary class that constructs SQL query statements. Sqlitequerybuilder qb = new sqlitequerybuilder ();//Getreadabledatabase (): Open the database read-write first, if the database disk space is full, will open the failure, when the failure of Open will continue to try to open the database read-only sqlitedatabase db = Dbhelper.getreadabledatabase (); qb.settables (table_name);/** * cursor is a collection of each line * In Android query data is implemented through the cursor class. When we use the sqlitedatabase.query () method, we get the Cursor object, and * cursor points to every piece of data */cursor c = qb.query (Db, projection, selection, null, null, null, sortorder); C.setnotificationuri (GetContext (). Getcontentresolver (), uri); return c;} @Overridepublic int update (uri arg0, contentvalues arg1, string arg2, STRING[] ARG3) {return 0;}}
To register in Androidmanifest.xml:
<application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/ Apptheme " > <activity android:name= ". Mainactivity " android:label=" @string/ App_name " > <intent-filter > <action android:name= "Android.intent.action.MAIN" /> <category android:name="Android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name= ". Mycontentprovider " android:authorities= "Com.archer.ContentProvider" > </ provider> <!-- android: The authorities property is configured with the name of the ContentProvider, which is the name of the Android system, and we are looking for the corresponding ContentProvider object by this name--> </application>
Finally, create a new project (for testing)
Package com. Contentproviderdemo.archer;import android.app.activity;import android.content.contentvalues;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.util.log;/** * access to the created database in another project without registering provider, otherwise it will be saved * @author administrator * */public class mainactivity extends activity {public static final String AUTHORITY = "Com.archer.ContentProvider";p Rivate uri content_ Uri = uri.parse ("content://" + authority); @Overrideprotected void oncreate ( bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main ); Insertrecord ("Record1");d isplayrecords (); }//inserting data Private void insertrecord (string UserName) {contentvalues values = new contentvalues (); Values.put ("USER_NAME", UserName); getcontentresOlver (). Insert (content_uri, values);} Query data private void displayrecords () {// The array contains all the fields to return string columns[] = new string[] { "_id", "user_name" }; uri myuri = content_uri; Cursor cur = getcontentresolver (). query (myuri, columns, null, null,null); if (Cur.movetofirst ()) {String id = null; String username = null;do {id = cur.getstring (Cur.getColumnIndex ("_id")); Username = cur.getstring (Cur.getcolumnindex ("user_name")); LOG.E ("TAG", "ID:" + id + ";" + "UserName:" + username);} while (Cur.movetonext ());} Cur.close (); // close cursor Object}}
In this way, data sharing between different applications is first
Android four components of content Provider