ContentProvider of the four Components (ii)-Easily customize ContentProvider

Source: Internet
Author: User

3rd Section Custom ContentProvider

Custom one ContentProvider , need

    1. Inheritance ContentProvider类 re-creates a class and implements some of these methods;
    2. In the applied AndroidManifest.xml file, declare the newly added component;

But before we do, we're going to design an external access to the address it uses.

3.1 Address Design

UriThe scheme fields are fixed and used content: .

authorityDefines the package name as a program com.anddle.mycontentprovider .

pathIt is like the classification within the site, according to the logic of the site division.
Suppose we have a ContentProvider query operation that provides book books and file two kinds of content. Each type can operate on a single data operation and multiple data operations.

For example

    • Information on the operation of all books: content://com.anddle.mycontentprovider/books ;
    • To manipulate the information of a particular book:content://com.anddle.mycontentprovider/books/8
    • To manipulate all file information:content://com.anddle.mycontentprovider/files
    • To manipulate information for a particular file:content://com.anddle.mycontentprovider/files/3

Therefore, when the objects represented by these addresses are added and censored, it is necessary to analyze the objects they target.

3.2 Creating a ContentProvider subclass
  1. Inheritance ContentProvider类 , will require US getType() insert() delete() update() query() onCreate() to implement such interfaces,

     Public  class mycontentprovider extends contentprovider {    @Override     Public Boolean onCreate() {return true; }@Override     PublicStringGetType(URI Uri) {Throw NewUnsupportedoperationexception ("not yet implemented"); }@Override     PublicUriInsert(URI Uri, contentvalues values) {Throw NewUnsupportedoperationexception ("not yet implemented"); }@Override     Public int Delete(Uri Uri, String selection, string[] Selectionargs) {Throw NewUnsupportedoperationexception ("not yet implemented"); }@Override     Public int Update(URI Uri, contentvalues values, String selection, string[] Selectionargs) {Throw NewUnsupportedoperationexception ("not yet implemented"); }@Override     PublicCursorQuery(Uri Uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {Throw NewUnsupportedoperationexception ("not yet implemented"); }}
  2. Defines the "network address" URI that is provided for use by other components, where we define them as content://com.anddle.mycontentprovider/books content://com.anddle.mycontentprovider/files

    Private Static FinalString SCHEME ="content://";Private Static FinalString Path_books ="/books";Private Static FinalString Path_files ="/files"; Public Static FinalString authority ="Com.anddle.mycontentprovider";//"Content://com.anddle.mycontentprovider/books" Public Static FinalUri Content_books_uri = uri.parse (SCHEME + authority + path_books);//"Content://com.anddle.mycontentprovider/files" Public Static FinalUri Content_files_uri = uri.parse (SCHEME + authority + path_files);
  3. Defines the match that resolves the address,

    Private Static Final intBOOKS =0;Private Static Final intBook =1;Private Static Final intFILES =2;Private Static Final intFILE =3;Private Static FinalUrimatcher Surimatcher;Static{Surimatcher =NewUrimatcher (Urimatcher.no_match);    Surimatcher.adduri (authority, Path_books, BOOKS); Surimatcher.adduri (Authority, path_books+"/#", book);    Surimatcher.adduri (authority, Path_files, FILES); Surimatcher.adduri (Authority, path_files+"/#", FILE);}

    UriMatcherThe incoming string can be matched for detection, and if the match succeeds, a corresponding value is returned, for example,

    int type = sUriMatcher.match("content://com.anddle.mycontentprovider/files");//type就等于FILES的值2

    The type is equal to the value of files 2. With this approach, we can distinguish ContentProvider what data is expected to be manipulated when a URI is accessed.

    When creating a match, add sUriMatcher.addURI("content://com.anddle.mycontentprovider","files/#", FILE); this key field with "#" to indicate the match, which matches any number

    content://com.anddle.mycontentprovider/files/0content://com.anddle.mycontentprovider/files/1content://com.anddle.mycontentprovider/files/3

    When creating a match, add sUriMatcher.addURI("content://com.anddle.mycontentprovider","files/*", FILE); this key field with "#", which means matching any character as follows

    content://com.anddle.mycontentprovider/files/how-to-programcontent://com.anddle.mycontentprovider/files/biblecontent://com.anddle.mycontentprovider/files/101story
  4. In the callback function, according to the URI, do the corresponding operation,

    @Override PublicUriInsert(URI Uri, contentvalues values) {Uri result =NULL;?Switch(Surimatcher.match (URI)) { CaseBOOKS: {//Remove the data from the contentvalues, save it; Returns the URI address of the saved data, for example            //content://com.anddle.mycontentprovider/books} Break; CaseBook: {//Remove the data from the contentvalues, save it; Returns the URI address of the saved data, for example            //CONTENT://COM.ANDDLE.MYCONTENTPROVIDER/BOOKS/8} Break; CaseFILES: {//Remove the data from the contentvalues, save it; Returns the URI address of the saved data, for example            //content://com.anddle.mycontentprovider/files} Break; CaseFILE: {//Remove the data from the contentvalues, save it; Returns the URI address of the saved data, for example            //CONTENT://COM.ANDDLE.MYCONTENTPROVIDER/FILES/8} Break;default:Throw NewIllegalArgumentException ("Unknown URI"+ URI); }returnResult;}

    It is necessary to realize the real operation of data deletion and change.

    In ContentProvider , you can save and modify data in a number of ways, such as a SQL database. But we're not going to do this for the time being, put it in the next section.

    Other delete() update() query() implemented functions do similar processing.

  5. For getType() , a data type that needs to be returned for each type Uri - MIME type tells the caller what type of data the current URI can handle.

    It has a format like type\subtype , there are many well-known MIME type types, such as, and application/pdf image/jpeg so on, can be found on the web to open the MIME type types of what. You can also customize the special types that your app supports MIME type .

    Here we return a null value,

    @OverridepublicgetType(Uri uri) {   returnnull;}

At this point, one ContentProvider is finished. However, it has not yet added the ability to actually store data.

/*******************************************************************/
Copyright notice
This tutorial is only available on CSDN and the Bean network, and this tutorial is hotlinking for other sites.
/*******************************************************************/

3.3 Declaration ContentProvider
Don't forget to declare new additions in the application's AndroidManifest.xml files, ContentProvider

<provider    android:name=".MyContentProvider"    android:authorities="com.anddle.mycontentprovider"    android:enabled="true"    android:exported="true" />

The attribute value here is to android:authorities fill in the definition MyContentProvider , the one in the code,

publicstaticfinal"com.anddle.mycontentprovider";

android:exportedHow the property is set true , which means that this can be ContentProvider used by other apps (like a public website that can be accessed by anyone), if set false to, indicates that it can only be used by its own application (just like an internal Web site, accessible only within the company).

3.4 Using Custom ContentProvider

Whether you're using your app ContentProvider or other apps, they're used just as you would with systems ContentProvider ,

  1. Add a piece of data data: by ContentResolver getting access to ContentProvider the portal, using ContentValues the Add data to be inserted;

    new ContentValues();cv.put("数据字段名称""数据内容");Uri uri = cr.insert("content://com.anddle.mycontentprovider/books", cv)

    It is usually returned to the data that was just successfully inserted Uri (as in the content content://com.anddle.mycontentprovider/books/8 ).

  2. Delete one data: Get access to ContentProvider via contentresolver , and use Uri to delete the specified data;

    string where = null ; String [] keywords = null ; Contentresolver CR = Getcontentresolver (); Cr.delete ( "content:// Com.anddle.mycontentprovider/books/8 ", where, keywords);  
  3. Modifies a data: Gets access to ContentProvider via contentresolver and updates the specified data using the Uri . The data to be modified is placed in contentvalues ;

    string where = null ; String [] keywords = null ; Contentresolver CR = Getcontentresolver (); Contentvalues CV = new  contentvalues (); Cv.put ( "data field name" , , where,keywords), Cr.update ( "content ://com.anddle.mycontentprovider/books ", CV, where, keywords)  
  4. Querying a class of data (or a particular piece of data),

    nullnullnullnull;ContentResolver resolver = getContentResolver();Cursor cursor = resolver.query(                    uri,                    searchKey,                     where,                     keywords,                     sortOrder);ifnull){    while(cursor.moveToNext())    {           ......      }    cursor.close();}

Note that parameters such as these are used in the operation of the redaction, which where sortOrder keywords searcgKey are used to assist in ContentProvider querying specific data.

Although it Uri has been able to locate a specific data, but most of ContentProvider it is through the SQL database to implement the real storage, so in the design of these interfaces to retain some of the SQL language usage, so that users can also be directly operational SQL database as flexible and convenient to use ContentProvider.

If you do ContentProvider not use SQL to implement data storage, and other storage mechanisms, then these additional parameters can be used in other useful or completely unnecessary.

ContentProvider of the four Components (ii)-Easily customize ContentProvider

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.