Android Four components content provider--contentprovider

Source: Internet
Author: User

Android four components of the content provider--contentprovider 1, what is the Contentprovidercontentprovider app to share the data in other applications, To provide the method of adding and removing changes ContentProvider unifies the way data is accessed, without having to take different access policies for different data types ContentProvider encapsulate the data. Only exposes the data we want to provide to other programs ContentProvider can register the observer, listen to changes in data 2, how to create 2.1 definition class inheritance ContentProvider, implement abstract method 2.2 Register in the manifest file: in the manifest file < Configure <provider> label under the application> node, you need to specify the name and authorities property in the label name: The full class name. You can omit the package name (the packages value of the manifest node), and note that the omitted class name is "." Start with. Authorities: is the path to access provider, to the unique 3, on the phone to register the app installed on the phone, do not run program 4, How other applications access external applications use the Contentresolver class to access data in ContentProvider (CRUD operations) Get the parser contentresolvercontentresolver resolver = Context.getcontentresolver (), access URI associated ContentProvider5 by Resolver.insert (), delete (), update (), query () method,   The URI processing URI represents the data to be manipulated, consisting of scheme, authorites, path three parts Eg:content://com.jxn.provider/personscheme | authorites | Path1,schema: Indicates that you want to access ContentProvider. Fixed to: "content://" 2,authority (hostname or authorization): Defines which ContentProvider provides the data. 3,path: path that can be customized according to business logic. Eg:person, Person/insert, PERSON/INSERT/10, and so on 4,id: Usually the URI is defined using the "#" placeholder instead, replaced with the corresponding number "Content://com.jxn.provider/person/# "#表示数据id (#代表任意数字)" content://com.jxn.provider/person/* "* to match any text. The Android system provides two tool classes for manipulating URIs: the Urimatcher and Contenturis 1,urimatcher classes are used to match URIs, using the following: The first step: The URI path you need to match all to the registration, as follows:// The constant Urimatcher.no_match represents a return code that does not match any path urimatcher matcher = new Urimatcher (urimatcher.no_match);//if the match () method matches the content ://com.jxn.provider.personprovider/person path, return match code to 1matcher.adduri ("Com.jxn.provider.personprovider", "person", 1 );//Add the need to match the URI, if the match will return the match code//if the match () method matches the content://com.jxn.provider.personprovider/person/230 path, Return match code to 2matcher.adduri ("Com.jxn.provider.personprovider", "person/#", 2);//#号为通配符第二步: Using Matcher.match (URI) The Matcher.match method matches the Uri of the input and returns the match Code switch (uri.parse ("CONTENT://COM.JXN.PROVIDER.PERSONPROVIDER/PERSON/10") if the match succeeds. ) {case 1//corresponding business operation Break;case 2//corresponding business operation break;default://corresponding business operation break;} The 2,contenturis class is used to get the URI plus Id:ContentUris.withAppendedId (URI, id) for the path plus ID and get the ID of the path id:ContentUris.parseId (URI) 6, listen to the content provider data Change 1, if the ContentProvider visitor needs to know that the data in the ContentProvider has changed, can be called Getconten when the ContentProvider data changes.Tresolver (). Notifychange (URI, NULL) to notify the visitor registering on this URI, for example: public class Personcontentprovider extends ContentProvider { Public URI inserts (URI Uri, contentvalues values) {Db.insert ("person", "PersonID", values);//Note: If the Notifychange () method is not called, Even if other applications register for Contentobserver, there is no known change in the data in ContentProvider getcontext (). Getcontentresolver (). Notifychange (URI, NULL);}} 2, if a contentprovider visitor needs to be notified of data changes, the data must be monitored using contentobserver (URI description), and when the monitor hears the data change notification, The system calls Contentobserver's OnChange () method: Getcontentresolver (). Registercontentobserver (Uri.parse ("content:// Com.jxn.providers.personprovider/person "), True, new Personobserver (New Handler ()));p Ublic class Personobserver Extends Contentobserver{public personobserver (Handler Handler) {super (Handler);} The public void OnChange (Boolean selfchange) {///can be used here for the appropriate business processing}}7, supplementing the GetType () method: primarily for matching data types, returning the MIME type of the data represented by the current URI. If the return data is a single piece of data: Vnd.android.cursor.item If the return data is multiple data: Vnd.android.cursor.dir case: B app accesses the data in a application via the ContentProvider provided by the A app// Provides Sqliteproviderpublic class Sqliteprovider defined in a application of ContentProvider Extends ContentProvider {//URI match, used to match incoming uriprivate static final urimatcher matcher = new Urimatcher (URIMATCHER.NO_MATC H);p rivate static final int person = 1;//Dbopenhelper extends sqliteopenhelperprivate dbopenhelper helper;static {//Set a Uri, if matched to person, returns 1matcher.adduri ("Com.jxn.sqlite.provider", "person", person); Other applications when the first access (at this time creates ContentProvider) executes//executes at the first boot, and then stays in the background for a long time, unless killed, @overridepublic Boolean onCreate () {Helper = New Dbopenhelper (GetContext ()); return true;} External apps Use this method to query data @overridepublic Cursor query (Uri uri, string[] projection, String selection, string[] Selectionargs, Stri ng SortOrder) {sqlitedatabase db = Helper.getreadabledatabase ();//Match the incoming Uriswitch (Matcher.match (URI)) with a match {case person : Return db.query ("person", projection, selection, Selectionargs, NULL, NULL, sortOrder);//Execute Query Default:throw new RuntimeException ("URI not recognized:" + URI);}} External apps Use this method to add data @overridepublic uri insert (URI uri, contentvalues values) {sqlitedatabase db = Helper.getwritabledatabASE (); switch (Matcher.match (URI)) {case Person:long id = db.insert ("person", "id", values);//insert record, get Idreturn Contenturi S.withappendedid (URI, id);//The ID is followed by the URI returned Default:throw new RuntimeException ("uri unrecognized:" + URI);}} @Overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {Sqlitedatabase db = Helper.getwritabledata Base (); Switch (Matcher.match (URI)) {case Person:return db.delete ("person", selection, Selectionargs);d Efault:throw New RuntimeException ("URI not recognized:" + URI);}} @Overridepublic int update (URI uri, contentvalues values, String selection, string[] selectionargs) {Sqlitedatabase db = h Elper.getwritabledatabase (); switch (Matcher.match (URI)) {case Person:return db.update (' person ', values, selection, Selectionargs);d efault:throw new RuntimeException ("URI not recognized:" + URI);}} @Overridepublic String getType (Uri uri) {switch (Matcher.match (URI)) {case Person:return "vnd.android.cursor.dir/ Person ";//Mimetypedefault:throw new RuntimeException (" URI not recognized: "+ URI);}}} B in ApplicationTest class to access data for a application public class Providertest extends Androidtestcase {public void Test () {//Get parser object Contentresolver resolver = g Etcontext (). Getcontentresolver ();//access content provider URI URI = Uri.parse ("Content://com.jxn.sqlite.provider"); Contentvalues values = new Contentvalues ();} public void Testquery () {//Gets the parser object Contentresolver resolver = GetContext (). Getcontentresolver (); Uri uri = uri.parse ("Content://com.jxn.sqlite.provider/person");//access content provider Cursor c = resolver.query (URI, new string[]{" ID "," name "," Balance "}," BALANCE&GT;? ", New string[]{" 9000 "}," balance DESC "), while (C.movetonext ()) {person p = new P Erson (c.getint (0), c.getstring (1), C.getint (2)); SYSTEM.OUT.PRINTLN (P);}} public void Testinsert () {Contentresolver resolver = GetContext (). Getcontentresolver (); Uri uri = uri.parse ("Content://com.jxn.sqlite.provider/person"); Contentvalues values = new Contentvalues () values.put ("name", "Provider"), Values.put ("balance", 12345);//Insert data, And get the Uriuri of this data = Resolver.insert (URI, values); System.out.priNtln (URI);} public void Testupdate () {Contentresolver resolver = GetContext (). Getcontentresolver (); Uri uri = uri.parse ("Content://com.jxn.sqlite.provider/person"); Contentvalues values = new Contentvalues (), Values.put ("name", "Update"), Values.put ("balance", 54321); int count = Resolver.update (URI, values, NULL, NULL); System.out.println (count);} public void Testdelete () {Contentresolver resolver = GetContext (). Getcontentresolver (); Uri uri = uri.parse ("Content://com.jxn.sqlite.provider/person"); int count = Resolver.delete (URI, NULL, NULL); System.out.println (count);} public void Testgettype () {Contentresolver resolver = GetContext (). Getcontentresolver ();//Gets the type of URI string type = Resolver.gettype (Uri.parse ("Content://com.jxn.sqlite.provider/person")); System.out.println (type);}}

Android Four components content provider--contentprovider

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.