(Android Review) Basic use of ContentProvider

Source: Internet
Author: User

1. Some databases are not available on the outside.
2, ContentProvider let a program in the data can let the B program use
3, ContentProvider is mainly shared data. Contentobserver can be added to observe changes in the data
4. Authorities in <provider/> is mainly used to distinguish different provider
5, Content://cn.itcast.aqlite.provider ((/person)/id)
Analytical:
content://-----> Fixed notation, must have
Cn.itcast.aqlite.provider:------"Application name for this application
Person: Table Name


6, a application through the B application of the ContentProvider Access B application Database


7, the use of ContentProvider query several ways:
1) without table name
2) only representative name

3) with table name and ID


This is the case with the previous example.

1, Sqliteprovider

Package Com.example.provider;import Com.example.sqlitetest.dbopenhelper;import Android.content.ContentProvider; Import Android.content.contenturis;import Android.content.contentvalues;import Android.content.urimatcher;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.net.Uri;import Android.widget.switch;public class Sqliteprovider extends ContentProvider {private Urimatcher matcher;private Dbopenhelper helper;public static final int person = 1;public static final int person_id = 2;private Sqlitedatabase db; @Ov Erridepublic Boolean onCreate () {//is executed on first boot, will reside in the background for a long time, and will not be executed unless killed. Matcher = new Urimatcher (urimatcher.no_match); Matcher.adduri ("Com.example.provider", "person", person);//Set a URI, If matched to person, returns 1matcher.adduri ("Com.example.provider", "person/#", person_id); helper = new Dbopenhelper (GetContext ( )); return true;} @Overridepublic Cursor query (Uri uri, string[] projection, string selection,string[] Selectionargs, string sortOrder) {Sy Stem.out.println ("--------->query");d B = helper.getreadabledatabase (); switch (Matcher.match (URI)) {case Person_id:long ID = Contenturis.parseid (URI);//Gets the URI of the last id//selection = "id=" + ID; Add the ID to the query condition. This method only solves the condition of the query with ID only selection = Selection = = null? "Id=" + id:selection+ "and id=" + id;//This time can process the query conditions may not only have the case of the ID cases Person:return db.query ("person", projection, Selec tion, selectionargs,null, null, SortOrder);d efault:throw new RuntimeException ("Uri does not match");}} @Overridepublic String getType (Uri uri) {switch (Matcher.match (URI)) {case Person_id:return "with ID. Operation Specifies person"; Person:return "no ID. Operation All person";d efault:break;} return null;} @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 Contenturis.withappendedid (URI, id);d efault:throw new RuntimeException ("indicates illegal");}} @Overridepublic int Delete (URI Uri, String selection, string[] SelectioNargs) {Sqlitedatabase db = helper.getwritabledatabase (); switch (Matcher.match (URI)) {case Person_id:long ID = Contenturis.parseid (URI);//Gets the URI of the last id//selection = "id=" + ID; Add the ID to the query condition. This method only solves the condition of the query with ID only selection = Selection = = null? "Id=" + id:selection+ "and id=" + id;//This time can process the query conditions may not only have the case of the ID cases Person:return db.delete ("person", selection, Selec Tionargs);d efault:throw new RuntimeException ("Uri does not match");}} /** * Sometimes it may not change ... * don't know why * * @Overridepublic int update (URI uri, contentvalues values, String selection,string[] Selecti Onargs) {Sqlitedatabase db = helper.getwritabledatabase (); switch (Matcher.match (URI)) {case Person_id:long ID = Contenturis.parseid (URI);//Gets the URI of the last id//selection = "id=" + ID; Add the ID to the query condition. This method only solves the condition of the query with ID only selection = Selection = = null? "Id=" + id:selection+ "and id=" + id;//This time can process the query conditions may not only have the case of the ID cases Person://return db.delete ("person", selection, SEL Ectionargs); return db.update ("person", values, Selection, Selectionargs);d efault:throw new RuNtimeexception ("Uri cannot Match");}} @Override//public int update (URI uri, contentvalues values, String selection, string[] Selectionargs) {// Sqlitedatabase db = Helper.getwritabledatabase ()//switch (Matcher.match (URI)) {//matches incoming uri//case person_id://with a match Long id = Contenturis.parseid (URI);//Get URI Last id//selection = Selection = = null? "Id=" + id:selection + "and id=" + id;//Build Query conditions//case person://return db.update ("person", values, selection, Selectiona RGS);//default://throw new RuntimeException ("URI not recognized:" + URI);//}//}}


The other code in this example is actually the same as before. Thanks, ContentProvider, remember to add the appropriate registration code in the early androidmanifest.xml:

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




2, b application of the Providertest

Package Com.example.test;import Com.example.pojo.person;import Android.content.contentresolver;import Android.content.contentvalues;import Android.database.cursor;import Android.net.uri;import Android.test.androidtestcase;public class Providertest extends Androidtestcase {/** * The execution order of this program: *. class, Dex-&gt ;. apk, install, open process (open main thread), * Create a Providertest object (the way the member variable is here GetContext (), when there is no GetContext ()), SetContext () Test method, GetContext () */public void Test1 () {Contentresolver resolver = GetContext (). Getcontentresolver ();//Note that It is not possible to speak resolver as a global variable contentvalues values = new Contentvalues (); Uri parse = uri.parse ("Content://com.example.provider"); Resolver.insert (parse, values); Resolver.delete (parse, NULL, NULL); Resolver.update (parse, values, NULL, NULL); Resolver.query (parse, NULL, NULL, NULL, NULL);/** * content:// Com.example.provider: Decision to access the application's database */}public void Testquery () {Contentresolver resolver = GetContext (). Getcontentresolver ();/** * Content://com.example.proVider/person * content://Fixed notation * com.example.provider:authorities * Person: Table name *///uri Uri = Uri.parse ("Content://com.exa Mple.provider/person ");//query Uri URI = Uri.parse (" CONTENT://COM.EXAMPLE.PROVIDER/PERSON/10 ") without ID;//with ID for query// Cursor C = resolver.query (URI, NULL, "ID&GT;?", New string[]{"" "}, NULL); Cursor C = resolver.query (URI, NULL, NULL, NULL, NULL), while (C.movetonext ()) {person p = new Person (c.getint (0), C.getstrin G (1), C.getint (2)); SYSTEM.OUT.PRINTLN (P);}} public void Testinsert () {Contentresolver resolver = GetContext (). Getcontentresolver (); Uri uri = uri.parse ("Content://com.example.provider/person"); Contentvalues values = new Contentvalues (), Values.put ("name", "Li Kaifu"), Values.put ("balance", 12345); Uri Uri1 = Resolver.insert (URI, values);//Insert data and get UriSystem.out.println (URI1) of the data;} public void Testupdate () {Contentresolver resolver = GetContext (). Getcontentresolver ();//uri Uri = Uri.parse ("content:/ /com.example.provider/person/102 ");//Specify ID, modify only one record URI uri = Uri.parse (" Content:Com.example.provider/person ");//Do not specify an ID, modify the entire table contentvalues values = new Contentvalues (); Values.put (" Name "," Kaifu Lili "); Values.put (" balance ", 9999); Resolver.update (URI, values, NULL, NULL);} public void Testdelete () {Contentresolver resolver = GetContext (). Getcontentresolver (); Uri uri = uri.parse ("content://com.example.provider/person/104"); Resolver.delete (URI, NULL, NULL);} public void Testgettype () {Contentresolver resolver = GetContext (). Getcontentresolver (); String type1 = Resolver.gettype (Uri.parse ("Content://com.example.provider/person"));    String type2 = Resolver.gettype (Uri.parse ("content://com.example.provider/person/102")); System.out.println (type1); System.out.println (type2);}}


SOURCE Download:







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.