Android content provider component

Source: Internet
Author: User

Content Provider is one of the components of Android applications and is the only way to share data between applications, the main function of content provider is to store and retrieve data and provide data access excuses for other applications.

The Android system provides a series of content providers for some common data types (such as music, video, images, and mobile phone contacts), all of which are in the Android. provider package. With a specific license, you can access these content providers in your own developed applications.

There are two ways to share your data with other applications: Create your own content provier (that is, inherit from the subclass of contentprovider) or add your own data to the existing content provider. The latter must ensure that the existing content provider has the same data type and the write permission of the content provider. For content providers, the most important thing is the data model and Uri.

1. Data Model
Content providers provide the data they store to visitors in the form of data tables. Each row in the data table is a record, and each column is data of a specific type and meaning. Each data record contains a "_ id" value field, which uniquely identifies a data record.

2. Uri
Uri. Each content provider provides a public URI that uniquely identifies a data set. If a content provider manages multiple datasets, it will assign an independent URI for each dataset. The Uris of all content providers start with "content: //". "content:" indicates the schema managed by the content provider.

Uri is used in almost all content provider operations. Therefore, it is best to define a URI as a constant if it is a self-developed content provider, this simplifies the development and improves the maintainability of the Code.

First, we will introduce how to access the data in the content provider, and access the data in the content provider mainly through the contentresolver object, the contentresolver class provides member methods for querying, inserting, modifying, and deleting data in the content provider. Take the query as an example. to query a content provider, you must master the following information.

URI that uniquely identifies the content provider
The name of the data field to be accessed.
Data Type of the data field

Tip: to access a specific data record, you only need the ID of the record.

There are two methods to query the content provider: contentresolver's query () and activity object's managedquery (). Both receive the same parameters and return the same cursor object, the only difference is that the managedquery method allows the activity to manage the cursor lifecycle.

The managed cursor will call its own deactivate method to uninstall the activity when it is paused. When the activity returns to the running status, it will call its own requery method to re-query the generated cursor object. If an unmanaged cursor object wants to be managed by the activity, you can call the startmanagingcursor method of the activity.

 

Android applications can use files or sqllite databases to store data. Content provider provides a way to share data between multiple applications. For example, contact information can be accessed by multiple applications. Content Provider is a class that implements a set of standard methods used to provide data access for other applications.

The application can perform the following operations in content provider:
Query data

Modify data

Add data

Delete data


/Chapter10_contentprovider_01_test02/src/COM/Amaker/ch10/APP/mainactivity. Java

Package COM. amaker. ch10.app; import android. app. activity; import android. content. contenturis; import android. content. contentvalues; import android. database. cursor; import android.net. uri; import android. OS. bundle; import android. util. log; import COM. amaker. ch10.app. employees. employee; public class mainactivity extends activity {@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // Add insert (); // query (); // Update (); // query (); // Delete del (); // query ();} // deletion method private void del () {// Delete the record URI with ID 1 = contenturis. withappendedid (employee. content_uri, 1); // obtain contentresolver and delete getcontentresolver (). delete (Uri, null, null);} // update private void Update () {// update the record URI with ID 1 = contenturis. withappendedid (employee. content_uri, 1); contentvalues values = new contentvalues (); // Add employee information values. put (employee. name, "Hz. guo "); values. put (employee. gender, "male"); values. put (employee. age, 31); // obtain contentresolver and update getcontentresolver (). update (Uri, values, null, null);} // query private void query () {// query column array string [] projection = new string [] {employee. _ id, // 0 employee. name, // 1 employee. gender, // 2 employee. age // 3}; // query all memo information cursor c = managedquery (employee. content_uri, projection, null, null, employee. default_sort_order); // determines whether the cursor is null if (C. movetofirst () {// traverse the cursor for (INT I = 0; I <C. getcount (); I ++) {C. movetoposition (I); // obtain the name string name = C. getstring (1); string gender = C. getstring (2); int age = C. getint (3); // output log. I ("EMP", name + ":" + gender + ":" + age) ;}}// insert private void insert () {// declare URI uri = employee. content_uri; // instantiate contentvalues values = new contentvalues (); // Add employee information values. put (employee. name, "Amaker"); values. put (employee. gender, "male"); values. put (employee. age, 30); // obtain contentresolver and insert getcontentresolver (). insert (Uri, values );}}

/Chapter10_contentprovider_01_test02/src/COM/Amaker/ch10/APP/employees. Java

Package COM. amaker. ch10.app; import android.net. uri; import android. provider. basecolumns;/*** Address Book constant class */public final class employees {// authorization constant public static final string authority = "com. amaker. provider. employees "; Private Employees () {}// internal class public static final class employee implements basecolumns {// constructor private employee () {} // access URI public static final URI content_uri = Uri. parse ("content: //" + authority + "/employee"); // The content type is public static final string content_type = "Vnd. android. cursor. DIR/vnd. amaker. employees "; public static final string content_item_type =" Vnd. android. cursor. item/vnd. amaker. employees "; // default sorting constant public static final string default_sort_order =" name DESC "; // sort by name // table field constant public static final string name =" name "; // name public static final string gender = "gender"; // gender public static final string age = "Age"; // age }}

/Chapter10_contentprovider_01_test02/src/COM/Amaker/ch10/APP/employeeprovider. Java

Package COM. amaker. ch10.app; import Java. util. hashmap; 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; import COM. amaker. ch10. App. employees. employee; public class employeeprovider extends contentprovider {// Database Help class private dbhelper; // URI tool class Private Static final urimatcher surimatcher; // query and update conditions: Private Static final int Employee = 1; Private Static final int employee ID = 2; // query the column set Private Static hashmap <string, string> empprojectionmap; static {// URI matching tool class surimatcher = new urimatcher (urimatcher. no_match ); Surimatcher. adduri (employees. authority, "employee", employee); surimatcher. adduri (employees. authority, "Employee/#", employee_id); // instantiate the query column set empprojectionmap = new hashmap <string, string> (); // Add the query column empprojectionmap. put (employee. _ id, employee. _ id); empprojectionmap. put (employee. name, employee. name); empprojectionmap. put (employee. gender, employee. gender); empprojectionmap. put (employee. age, emplo Yee. age);} // create is to call public Boolean oncreate () {// instantiate the Database Help class dbhelper = new dbhelper (getcontext (); Return true ;} // Add the public URI insert (URI Uri, contentvalues values) {// obtain the database instance sqlitedatabase DB = dbhelper. getwritabledatabase (); // insert data, return row Id long rowid = dB. insert (dbhelper. employees_table_name, employee. name, values); // If the insert is successful, the returned URI if (rowid> 0) {URI empuri = contenturis. withappendedi D (employee. content_uri, rowid); getcontext (). getcontentresolver (). notifychange (empuri, null); Return empuri;} return NULL;} // Delete method public int Delete (URI Uri, string selection, string [] selectionargs) {// obtain the database instance sqlitedatabase DB = dbhelper. getwritabledatabase (); // get the int count of the database instance; Switch (surimatcher. match (URI) {// Delete case employee: Count = dB according to the specified condition. delete (dbhelper. employees_table_name, Selection, selectionargs); break; // Delete case employee_id: String noteid = URI according to the specified condition and ID. getpathsegments (). get (1); Count = dB. delete (dbhelper. employees_table_name, employee. _ ID + "=" + noteid + (! Textutils. isempty (selection )? "And (" + selection + ')': ""), selectionargs); break; default: Throw new illegalargumentexception ("wrong Uri" + URI);} getcontext (). getcontentresolver (). categorychange (Uri, null); Return count;} // obtain the Public String GetType (URI) {return NULL;} // query method public cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder) {sqlitequerybuilder QB = new Sqlitequerybuilder (); Switch (surimatcher. match (URI) {// query all case employee: QB. settables (dbhelper. employees_table_name); QB. setprojectionmap (empprojectionmap); break; // query case employee_id: QB by ID. settables (dbhelper. employees_table_name); QB. setprojectionmap (empprojectionmap); QB. appendwhere (employee. _ ID + "=" + Uri. getpathsegments (). get (1); break; default: Throw new illegalargumentexception ("URI error! "+ URI) ;}// use the default sorting string orderby; If (textutils. isempty (sortorder) {orderby = employee. default_sort_order;} else {orderby = sortorder;} // obtain the database instance sqlitedatabase DB = dbhelper. getreadabledatabase (); // returns the cursor set cursor c = QB. query (dB, projection, selection, selectionargs, null, null, orderby); C. setnotificationuri (getcontext (). getcontentresolver (), Uri); Return C ;}// update method public int updat E (URI Uri, contentvalues values, string selection, string [] selectionargs) {// obtain the database instance sqlitedatabase DB = dbhelper. getwritabledatabase (); int count; Switch (surimatcher. match (URI) {// update case employee: Count = dB according to specified conditions. update (dbhelper. employees_table_name, values, selection, selectionargs); break; // update case employee_id: String noteid = URI Based on the specified conditions and ID. getpathsegments (). get (1); Count = dB. update (Dbhelper. employees_table_name, values, employee. _ ID + "=" + noteid + (! Textutils. isempty (selection )? "And (" + selection + ')': ""), selectionargs); break; default: Throw new illegalargumentexception ("wrong Uri" + URI);} getcontext (). getcontentresolver (). notifychange (Uri, null); Return count ;}}

/Chapter10_contentprovider_01_test02/src/COM/Amaker/ch10/APP/dbhelper. Java

 

Package com. Amaker. ch10.app;

Import Android. content. context;
Import Android. database. SQLite. sqlitedatabase;
Import Android. database. SQLite. sqliteopenhelper;
Import com. Amaker. ch10.app. Employees. employee;
/**
*
* Database tools
*/
Public class dbhelper extends sqliteopenhelper {
// Database name constant
Private Static final string database_name = "employees. DB ";
// Database version constant
Private Static final int database_version = 1;
// Table name constant
Public static final string employees_table_name = "employee ";
// Constructor
Public dbhelper (context ){
// Create a database
Super (context, database_name, null, database_version );
}

// Called at creation
Public void oncreate (sqlitedatabase dB ){
Db.exe csql ("create table" + employees_table_name + "("
+ Employee. _ ID + "integer primary key ,"
+ Employee. Name + "text ,"
+ Employee. Gender + "text ,"
+ Employee. Age + "integer"
+ ");");
}

// Called when the version is updated
Public void onupgrade (sqlitedatabase dB, int oldversion, int newversion ){
// Delete a table
Db.exe csql ("Drop table if exists employee ");
Oncreate (db );
}

}

/Chapter10_contentprovider_01_test02/androidmanifest. xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.amaker.ch10.app"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">

<provider android:name="EmployeeProvider"
android:authorities="com.amaker.provider.Employees"/>

<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>

</application>
<uses-sdk android:minSdkVersion="3" />

</manifest>


Related Article

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.