Android Learning _contentprovider and URIs

Source: Internet
Author: User

ContentProvider Overview

Public abstract class

ContentProvider

Extends Object

Implements COMPONENTCALLBACKS2

Content providers is one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single Contentresolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data are used by multiple applications and must being stored in a content provider. If you don't need to share the data amongst multiple applications you can use a database directly via Sqlitedatabase.

When a request was made via a contentresolver the system inspects the authority of the given URI and passes the request to The content provider registered with the authority. The content provider can interpret the rest of the URI however it wants. The Urimatcher class is helpful for parsing URIs.

The ContentProvider role of Android is to exchange data between applications, and if we take a file share, we need to be aware that certain data access methods are required, and ContentProvider is the standard API for exchanging data between different applications. ContentProvider provides data externally in the form of a URI, while other applications use Contentresolver to specify data based on the URI to access the operation.

ContentProvider is also one of the four components of Android apps, similar to activity, Service, and Broadcastreceiver, and needs to be configured in the Androidmanifest.xml file.

Use of ContentProvider
    The
    • defines its own ContentProvider class, inherits the child ContentProvider base class,
    • is registered in the Androidmanifest.xml file, and binds a URL.

      Public class Imagecontentprovider extends contentprovider{

       // This method is used for external applications to delete data from contentprovider @overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {return 0; }//The method is used to return the MIME type of the data represented by the current URL @overridepublic String getType (Uri uri) {return null;} This method is used for external applications to add data to ContentProvider @overridepublic URI insert (URI uri, contentvalues values) {return null;}    This method is called after ContentProvider is created, and after Android is turned on, ContentProvider is created @overridepublic boolean onCreate () when the other app accesses it for the first time () { return false;} This method is used for external applications to get data from ContentProvider @overridepublic Cursor query (Uri URI, string[] values, String selection, string[] Selectionargs, String sortOrder) {return null;} This method is used for external applications to update data in contentprovider @overridepublic int update (URI uri, contentvalues values, String selection, string[] Selectionargs) {return 0;}  

      }

If the data of the operation belongs to the collection type, then the MIME type string should start with vnd.android.cursor.dir/.

For example: To get the URI for all person Records is Content://com.ljq.provider.personprovider/person, then the MIME type string returned should be: " Vnd.android.cursor.dir/person ".

If the data to be manipulated belongs to non-collection type data, then the MIME type string should start with vnd.android.cursor.item/.

For example: Get the person record with ID 10, the URI is CONTENT://COM.LJQ.PROVIDER.PERSONPROVIDER/PERSON/10, and the MIME type string returned is: " Vnd.android.cursor.item/person ".

Registering ContentProvider only needs to be

URI Overview

The URI is still easy to understand, and we can compare it to the URL of the Internet.

content://com.twilight.providers.imagecontentprovider/image/2

The meaning of this is to access a record with an image data total ID of 2. While most of the data that ContentProvider operates on is from the database, it can sometimes come from other storage methods such as file, XML, or network.

content://com.twilight.providers.imagecontentprovider/image/detail

The meaning of this is to manipulate the detail node under the image node.

URI Tool Class

The Android system provides 2 tool classes for manipulating URIs, namely Urimatcher and Contenturis.

(1) The Urimatcher class is used to match URIs

UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);matcher.addURI("com.twilight.providers.imageprovider", "image", 1);matcher.addURI("com.twilight.providers.imageprovider", "image/#", 2);switch (matcher.match(Uri.parse("content://com.twilight.providers.imageprovider/image/7"))) {    case 1:        break;    case 2:        break;    default:        break;}

After registering the URI that needs to be matched, the URI of the input is matched by the Matcher.match (URI) method, and the matching code is returned if the match is made.

(2) The Conenturis class is used to manipulate the ID portion following the URI path.

Uri uri1 = Uri.parse("content://com.twilight.providers.imageprovider/image");Uri resultUri = ContentUris.withAppendedId(uri1, 7);Uri uri2 = Uri.parse("content://com.twilight.providers.imageprovider/image/7");long resultId = ContentUris.parseId(uri2);
Manipulating data with Contentresolver

ContentProvider is equivalent to a website, while Contentresolver is relative to httpclient. In general, the content is a singleton pattern, and data operations are delegated to the same ContentProvider processing when multiple applications use Contentresolver to manipulate the data provided by ContentProvider.

(1) Call Activity Contentresolver () to get the Contentresolver object;
(2) using Contentresolover's INSERT, delete, update, query method to manipulate the data, if the system provides contentprovider, only need to know the ContentProvider URI.

ContentResolver resolver = getContentResolver();Uri uri = Uri.parse("content://com.twilight.providers.imageprovider/image");ContentValues values = new ContentValues();values.put("name", "pic1");values.put("date", "2014-03-10");resolver.insert(uri, values);
Monitor the ContentProvider data changes
getContext().getContentResolver().notifyChange(uri, null);

When the data shared by ContentProvider has changed, this line of code can notify all listeners registered to change the URI, in order to listen for changes in the ContentProvider data in the application, You need to use Android to provide the Contentobserver base class.

Listeners listening for contentprovider data changes need to inherit the Contentobserver class and override the OnChange (Boolean Selfchange) method defined by the change base class. You need to register the Contentobserver listener with ContentProvider to the specified URI when you use it.

        final class ImageObserver extends ContentObserver {            public ImageObserver(Handler handler) {                super(handler);            }            public void onChange(boolean selfChange) {            }        }        getContentResolver().registerContentObserver(Uri.parse("content://com.twilight.providers.imageprovider/image"),        true, new ImageObserver(new Handler()));

Android Learning _contentprovider and URIs

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.