Android data storage ---- ContentProvider Data Storage

Source: Internet
Author: User

ContentProvider encapsulates database operations and shares data. That is to say, the data storage implemented by ContentProvider can be accessed in external applications. The specific process is as follows:

I. Extended ContentProvider class provides data access interfaces

Extends the SQLiteOpenHelper class to create and update database tables. For more information, see the previous blog)

Note: We recommend that you extract the table name and column name of the database into a Global static constant to facilitate subsequent calls.

The database created here is quan. db. Database Table Name: user. The column name has two items: _ id Primary Key) and title. That is

Public class MySqlite extends SQLiteOpenHelper {// database table name. The column name is extracted as the Global static constant public static final String TABLE_NAME = "user"; public static final String TABLE_TITLE = "title "; public static final String TABLE_ID = "_ id"; // constructor public MySqlite (Context context) {super (context, "quan. db ", null, 1);} // create a database table @ Override public void onCreate (SQLiteDatabase db) {db.exe cSQL ("create table" + TABLE_NAME + "(" + TABLE_ID + "integer primary key autoincrement," + TABLE_TITLE + "text not null )");} // update the database table @ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){}}

2. Extend the ContentProvider abstract class to implement six abstract methods and encapsulate database operations.

1: URI Introduction

A uniform resource identifier (URI) is a string that uniquely identifies a resource. Similarly, ContentProvider also requires a unique string to identify the uniqueness of the data. It is also based on URI registration in the Manifest. xml file that external applications can find the data provided by ContentProvider.

Specific registration method:

<Provider android: name = "Class name inherited from ContentProvider class" android: authorities = "package name. Class name inherited from ContentProvider class"> </provider>

Specific URI format:

Public static final Uri URI = Uri. parse ("content: // package name. The class name inherited from Contentprovider, that is, the property value of android: authorities under registration )");

Note: The "content: //" in the string is in a fixed format.

2: Six abstract methods and their functions

1) onCreate (): Mainly used to initialize the used tool. It will be called after the ContentProvider object is created. For example, initialization of objects inherited from the SQLiteOpenHelper class and initialization of readable and writable objects in SQLiteDatabase.

2) query (): The return type is Cursor. You can query tables in an external application database by using the query method that has readable objects in the database. That is, external applications are provided to obtain data from ContentProvider.

3) insert (): The return type is Uri. The insert operation on the table of the database is completed through the insert method for objects with writable permissions on the database. That is, the external application inserts data into ContentProvider.

4) delete (): The return type is int. You can delete tables in the database by using the delete method that has the write permission to the database. That is, the external application deletes data from ContentProvider.

5) update (): The return type is int. update operations on tables in the database are completed by updating the database objects with writable permissions. The external application updates the data in ContentProvider.

6) getType (): identifies the Data Type in ContentProvider.

3: Implementation

Public class MyCP extends ContentProvider {// unified resource identifier public static final Uri = URI. parse ("content: // com. example. day08_mycontentprovider.MyCP "); // declare the database creation and update object private MySqlite mySqlite; // obtain the readable and writable Data Objects private SQLiteDatabase dbWriter and dbReader; // obtain the table name, static constants such as column names: private static final String CP_TABLE_NAME = MySqlite. TABLE_NAME; private static final String CP_TABLE_TITLE = MySqlite. TABLE_TITLE; private static final String CP_TABLE_ID = MySqlite. TABLE_ID; @ Override public boolean onCreate () {mySqlite = new MySqlite (getContext (); // create a database table dbWriter = mySqlite. getWritableDatabase (); // instantiate the readable and writable object dbReader = mySqlite. getReadableDatabase (); return true;} // query the table in the Database @ Override public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) {return dbReader. query (CP_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);} // query and insert a table in the Database @ Override public Uri insert (Uri uri, ContentValues values) {dbWriter. insert (CP_TABLE_NAME, null, values); return uri;} // delete a Database Table @ Override public int delete (Uri uri, String selection, String [] selectionArgs) {return dbWriter. delete (CP_TABLE_NAME, selection, selectionArgs);} // database update to the Table @ Override public int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) {return dbWriter. update (CP_TABLE_NAME, values, selection, selectionArgs);} // return data type @ Override public String getType (Uri uri Uri) {return null ;}}

3. Reference of internal applications

In an application, call several methods in ContentProvider by using the getContentResolver () method to complete table operations in data.

Public class MainActivity extends Activity {// obtain the URI public Uri uri = MyCP that uniquely identifies ContentProvider. URI; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); addDB (); // updateDB (); // deleteDB (); selectDB () ;}// add by getContentResolver () obtain the ContentProvider's data parsing object public void addDB () {ContentValues cv = new ContentValues (); cv. put ("title", "HelloWord"); getContentResolver (). insert (uri, cv); // call the insert method of ContentProvider to add data} // query public void selectDB () {// call the query method of ContentProvider, implement Data Query Cursor cursor = getContentResolver (). query (uri, null, null); while (cursor. moveToNext () {System. out. println (cursor. getString (cursor. getColumnIndex ("title");} // modify public void updateDB () {// call the ContentProvider update method to modify ContentValues cv = new ContentValues (); cv. put ("title", "I renamed it, my name is James"); getContentResolver (). update (uri, cv, null, null);} // delete public void deleteDB () {// call the delete method of ContentProvider to delete getContentResolver (). delete (uri, null, null );}}

Iv. External Application reference

1: extract the unique identifier URI of ContentProvider as a static constant. Its value is the same as above.

2: Call several methods in ContentProvider through the getContentResolver () method to complete table operations in data.

Public class MainActivity extends Activity {// extract the Uniform Resource Identifier URI to obtain the public static final Uri URI = Uri of the data stored by ContentProvider. parse ("content: // com. example. day08_mycontentprovider.MyCP "); @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); selectDB (); // call method} // call several methods in ContentProvider by using the getContentResolver () method to complete table operations in Data . Public void selectDB () {Cursor cursor = getContentResolver (). query (URI, null, null); while (cursor. moveToNext () {System. out. println (cursor. getString (cursor. getColumnIndex ("title ")));}}}

5. Results

Internal application: tables in the database exist in data/package name/database/***. db, Export, and use SQLite Export to view data in the table

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10413I555-0.png "title =" 1.png"/>

External applications: output table data in the database on the console

08-31 10:31:39.158: I/System.out(285): HelloWord


The sound is starting... 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10413L0X-1.gif "/>




This article is from the "Schindler" blog, please be sure to keep this source http://cinderella7.blog.51cto.com/7607653/1285960

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.