Customization of Android Components ContentProvider

Source: Internet
Author: User

There are five ways to store data on Android, such as shared Preferences, networked storage, file storage, storage, SQLite, and so on, typically these stores only have one data share in a single application, and sometimes we need to manipulate some data from other applications, For example, the common system of contacts, text messages, photos and so on, so cloud storage, contacts, photo scandal and so on the birth. ContentProvider can be understood as a content provider, or as an interface, which provides an interface for external access, sometimes requiring permission control.

ContentProvider Introduction

ContentProvider provides us with a mechanism to share data before the application, and we know that each application is running in a different application, and that data sharing between different programs is a real need, and the program cannot always make the closed loop, The benefit of sharing data outside of ContentProvider in Android is to unify the way data is accessed. Briefly summarize:

    1. ContentProvider provides a unified interface for storing and retrieving data. Contentprovide encapsulates the data without worrying about the details of the data store. Use the form of tables to organize your data.
    2. Using ContentProvider, you can share data between different applications.
    3. Android provides default contentprovider for some common data (including audio, video, images, contacts, and so on).

Speaking of ContentProvider so many benefits, can not say the URI (Universal Resource Identifier) Note is not a URL, a generic resource identifier, see a simple read the URI of the contact, content:// Contacts/people,

    1. content://is a prefix, fixed;
    2. The contacts hostname (or authority) is used to uniquely identify this contentprovider, which can be invoked by an external caller;
    3. The People Path (path) represents the data we want to manipulate, and the path is built according to the business;
Custom ContentProvider

As the saying goes, to be good its prerequisite, want to become a content provider, first need to have data, first establish a sqldbconncetion:

public class Sqldbconnection extends Sqliteopenhelper {private static final String DbName = "book.db";p rivate static int ve Rsion=1;public sqldbconnection (Context context) {Super (context, DbName, NULL, version);} @Overridepublic void OnCreate (Sqlitedatabase db) {//TODO auto-generated method stub String sqlstring= "CREATE TABLE book ( ID integer PRIMARY key autoincrement,name nvarchar ($), Title nvarchar (200)) "; Db.execsql (sqlString);} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method stub}}

The JUnit tests in the previous article can be used at this time to initialize the following data:

public class Bookcase extends Androidtestcase {public void Intial () {sqldbconnection dbConnection = new Sqldbconnection (ge Tcontext ());  Sqlitedatabase sqldatabase = Dbconnection.getwritabledatabase (); Long row = 0;for (int i = 0; i < 5; i++) {contentvalues values = new Contentvalues (), Values.put ("Name", "book" +i), Values.put ("title", "title" + i); row = Sqldatabase.insert ("Books", n Ull, values); LOG.I ("Bookcase", "Insert success:" + Row);}}}

The front is the basic work, this time can build a own contentprovider:

public class Mycontentprovider extends ContentProvider {private static final String authority = "Com.example.googleconten Tprovider. Mycontentprovider ";p rivate static final int content_insert = 0;private static final int content_query = 1;private static F inal int content_delete = 2;private static final int content_update = 3;private static final int content_query_single = 4; private static Urimatcher urimatcher;private sqldbconnection dbConnection = null;static {urimatcher = new Urimatcher (Urim Atcher.no_match); Urimatcher.adduri (Authority, "Book/insert", Content_insert); Urimatcher.adduri (AUTHORITY, "book/ Query ", content_query); Urimatcher.adduri (Authority," Book/delete ", Content_delete); Urimatcher.adduri (AUTHORITY," Book/update ", content_update); Urimatcher.adduri (Authority," book/query/# ", Content_query_single);} @Overridepublic Boolean onCreate () {dbConnection = new sqldbconnection (GetContext ()); return true;} @Overridepublic Cursor query (Uri uri, string[] projection, String selection,string[] Selectionargs, String sortOrder) {sqlitedatabase dbdatabase = dbconnection.getwritabledatabase (); switch ( Urimatcher.match (URI)) {Case content_query:if (Dbdatabase.isopen ()) {Cursor cursor=dbdatabase.query ("book", Projection, selection, Selectionargs, NULL, NULL, NULL); return cursor;} Break;case content_query_single:if (Dbdatabase.isopen ()) {long Id=contenturis.parseid (URI); Cursor Cursor=dbdatabase.query ("book", Projection, "Id=?", New String[]{id+ ""}, NULL, NULL, NULL); return cursor; Break;default:break;} return null;} @Overridepublic String getType (Uri uri) {//TODO auto-generated method Stubreturn null;} @Overridepublic uri insert (URI uri, contentvalues values) {sqlitedatabase dbdatabase = dbconnection.getwritabledatabase (); switch (Urimatcher.match (URI)) {Case content_insert:if (Dbdatabase.isopen ()) {Long id = dbdatabase.insert ("book", NULL, values);d bdatabase.close (); return Contenturis.withappendedid (URI, id);} Break;default:break;} return null;} @Overridepublic int Delete (URI Uri, StrinG selection, string[] Selectionargs) {//TODO auto-generated method Stubsqlitedatabase dbdatabase = Dbconnection.getwrita Bledatabase (); switch (Urimatcher.match (URI)) {Case content_delete:if (Dbdatabase.isopen ()) {int count= Dbdatabase.delete ("book", Selection, Selectionargs);d bdatabase.close (); return count;} Break;default:break;} return 0;} @Overridepublic int update (URI uri, contentvalues values, String selection,string[] selectionargs) {sqlitedatabase Dbdatabase = dbconnection.getwritabledatabase (); switch (Urimatcher.match (URI)) {Case Content_update:if ( Dbdatabase.isopen ()) {int count= dbdatabase.update ("book", Values, Selection, Selectionargs);d bdatabase.close (); return count;} Break;default:break;} return 0;}}

Hostname is required to go to the Androidmanifest.xml files themselves configured, the requirements are unique, it is best to use the package name is good:

   <provider android:name= "Com.example.googlecontentprovider.MyContentProvider"            android:authorities= " Com.example.googlecontentprovider.MyContentProvider "></provider>

If you feel that the above string of code is not very good understanding, the following call I will explain separately.

Use of Contentresolver

Method written in one application is normal, the method that calls the program in another program is similar to the interface, the following first to look at the original initialized data:

re-create a new Android test project, defined as bookcase, first insert the data, define a URI, the host name is defined above the package name, Book/insert and Content_insert are the corresponding:

public void Bookinsert () {uri uri = uri.parse ("content://com.example.googlecontentprovider.mycontentprovider/book/ Insert "); Contentresolver resolver = GetContext (). Getcontentresolver (); Contentvalues values = new Contentvalues () values.put ("Name", "Book 5"), Values.put ("title", "title 5"); URI = Resolver.insert ( URI, values); LOG.I ("bookcase", "uri" + URI); Long id = Contenturis.parseid (URI); LOG.I ("Bookcase", "Test succeeded" + ID);}

The results appear as follows:

Then update the data just inserted, the same code to the URI assignment, and then initialize a contentresolver, call the Update method:

public void Bookupdate () {uri uri = uri.parse ("content://com.example.googlecontentprovider.mycontentprovider/book/ Update "); Contentresolver resolver = GetContext (). Getcontentresolver (); Contentvalues values=new contentvalues () values.put ("Name", "Modify"); int count = Resolver.update (URI, values, "Id=?", New string[]{"10"}); LOG.I ("Bookcase", "updated" + Count + "line");}

 The results are as follows:

To delete the inserted data:

public void Bookdelete () {uri uri = uri.parse ("content://com.example.googlecontentprovider.mycontentprovider/book/ Delete "); Contentresolver resolver = GetContext (). Getcontentresolver (); String where = "id=?"; String[] argstring = {"Ten"};int count = Resolver.delete (URI, where, argstring); LOG.I ("Bookcase", "deleted" + Count + "line");}

The results are as follows:

To query all data:

public void Bookquery () {uri uri = uri.parse ("content://com.example.googlecontentprovider.mycontentprovider/book/ Query "); Contentresolver resolver = GetContext (). Getcontentresolver (); Cursor  cursor=resolver.query (URI, new string[]{"id", "Name", "Title"}, NULL, NULL, NULL); if (Cursor.getcount () > 0) {while (Cursor.movetonext ()) {int Id=cursor.getint (CURSOR.GETCOLUMNINDEX ("id")); String namestring=cursor.getstring (Cursor.getcolumnindex ("Name")); String titlestring=cursor.getstring (Cursor.getcolumnindex ("Title")); LOG.I ("Bookcase", id+ "---" +namestring+ "---" +titlestring);}}}

Log log:

Query a single record:

public void Bookquerysingle () {uri uri = uri.parse ("content://com.example.googlecontentprovider.mycontentprovider/ Book/query "); Contentresolver resolver = GetContext (). Getcontentresolver (); Uri=contenturis.withappendedid (uri,1); Cursor  cursor=resolver.query (URI, new string[]{"id", "Name", "Title"}, NULL, NULL, NULL); if (Cursor.getcount () > 0) {while (Cursor.movetonext ()) {int Id=cursor.getint (CURSOR.GETCOLUMNINDEX ("id")); String namestring=cursor.getstring (Cursor.getcolumnindex ("Name")); String titlestring=cursor.getstring (Cursor.getcolumnindex ("Title")); LOG.I ("Bookcase", id+ "---" +namestring+ "---" +titlestring);}}}

Results:

At this point a custom contentprovider all done, if there is improper, please many advice ~

Custom ContentProvider for Android components

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.