ContentProvider customization and content providers for SMS and contacts

Source: Internet
Author: User

1. Custom content providers first create extends ContentProvider classes
 Packagecom.txs.db;ImportAndroid.content.ContentProvider;ImportAndroid.content.ContentValues;ImportAndroid.content.UriMatcher;ImportAndroid.database.Cursor;ImportAndroid.database.sqlite.SQLiteDatabase;ImportAndroid.net.Uri;/** * Content provider Backdoor, provides private data to other applications, default is empty implementation. * / Public  class bankdbbackdoor extends contentprovider {     Public Static Final intSUCCESS =1;/** * Create a security guard, check the URI rules if the URI match fails to return-1 */    StaticUrimatcher Murimatcher =NewUrimatcher (Urimatcher.no_match);Static{Murimatcher.adduri ("Com.txs.db","Account", SUCCESS); }@Override     Public int Delete(Uri Uri, String selection, string[] Selectionargs) {intCode = Murimatcher.match (URI);if(Code = = SUCCESS) {System.out.println ("Delete Deletes data"); Mydbopenhelper helper =NewMydbopenhelper (GetContext ());            Sqlitedatabase db = Helper.getwritabledatabase (); Db.delete ("Account", selection, Selectionargs);//Use the parser of the content provider to notify the content viewer that the data has changedGetContext (). Getcontentresolver (). Notifychange (URI,NULL); }Else{Throw NewIllegalArgumentException ("The password is not correct, roll Duzi"); }return 0; }@Override     PublicStringGetType(URI Uri) {return NULL; }@Override     PublicUriInsert(URI Uri, contentvalues values) {intCode = Murimatcher.match (URI);if(Code = = SUCCESS) {System.out.println ("Insert add Data"); Mydbopenhelper helper =NewMydbopenhelper (GetContext ());            Sqlitedatabase db = Helper.getwritabledatabase (); Db.insert ("Account",NULL, values);//Use the parser of the content provider to notify the content viewer that the data has changedGetContext (). Getcontentresolver (). Notifychange (URI,NULL); }Else{Throw NewIllegalArgumentException ("The password is not correct, roll Duzi"); }return NULL; }@Override     Public Boolean onCreate() {return false; }@Override     PublicCursorQuery(Uri Uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {intCode = Murimatcher.match (URI);if(Code = = SUCCESS) {System.out.println ("Query Data"); Mydbopenhelper helper =NewMydbopenhelper (GetContext ()); Sqlitedatabase db = Helper.getreadabledatabase ();returnDb.query ("Account", projection, selection, Selectionargs,NULL,NULL, SortOrder); }Else{Throw NewIllegalArgumentException ("The password is not correct, roll Duzi"); }    }@Override     Public int Update(URI Uri, contentvalues values, String selection, string[] Selectionargs) {intCode = Murimatcher.match (URI);if(Code = = SUCCESS) {System.out.println ("Update updates data"); Mydbopenhelper helper =NewMydbopenhelper (GetContext ());            Sqlitedatabase db = Helper.getwritabledatabase (); Db.update ("Account", values, selection, Selectionargs);//Use the parser of the content provider to notify the content viewer that the data has changedGetContext (). Getcontentresolver (). Notifychange (URI,NULL); }Else{Throw NewIllegalArgumentException ("The password is not correct, roll Duzi"); }return 0; }}
Manifest List Registered content provider
<provider            android:name="com.txs.db.BankDBBackdoor"            android:authorities="com.txs.db" >        </provider>
Parsing ContentProvider with Contentrsolver
ContentResolver resolver = getContentResolver();        Uri uri = Uri.parse("content://com.txs.db/account");//和清单文件中定义的主机名保持一致
SMS gets data through ContentProvider
Uri uri = Uri. Parse("Content://sms");//All SMSContentresolver resolver = Getcontentresolver ();Contentvalues values = new Contentvalues ();Values. Put("Address"," the");Values. Put("Date", the System. Currenttimemillis());Values. Put("Type",1);Values. Put("Body","Congratulations on your being named a good citizen, dare to help the old lady.");Resolver. Insert(URI, values);

Contacts getting data through ContentProvider
public static list<contactinfo> Getallcontactinfos (context context) {list<contactinfo> infos =NewArraylist<contactinfo> (); Contentresolver resolver = Context.getcontentresolver ();//Query Raw_contact tableUri uri = Uri.parse ("Content://com.android.contacts/raw_contacts"); Uri Datauri = Uri.parse ("Content://com.android.contacts/data"); cursor cursor = resolver.query (URI,New String[] {"contact_id"},NULL,NULL,NULL); while(Cursor.movetonext ()) {Stringid = cursor.getstring (0);if(id! =NULL) {ContactInfo info =NewContactInfo ();//Query data tableCursor datacursor = Resolver.query (Datauri,New String[] {"Data1","MimeType"},"raw_contact_id=?",New String[] {ID},NULL); while(Datacursor.movetonext ()) {StringData1 = datacursor.getstring (0);StringMimeType = datacursor.getstring (1);if("Vnd.android.cursor.item/name". Equals (MimeType)) {info.setname (data1); }Else if("Vnd.android.cursor.item/im". Equals (MimeType)) {info.setqq (data1); }Else if("Vnd.android.cursor.item/email_v2". Equals (MimeType)) {info.setemail (data1); }Else if("Vnd.android.cursor.item/phone_v2". Equals (MimeType)) {Info.setphone (data1);                }} datacursor.close ();            Infos.add (info); }} cursor.close ();returnInfos; }

Other people's summary: {

Ii. Introduction to the URI class

The URI represents the data to be manipulated, and the URI mainly contains two pieces of information
① need to operate the ContentProvider
② what data in the ContentProvider is being manipulated

Part
①scheme:contentprovider's scheme has been defined by Android as content://
② hostname (AUTHORITY): Used to uniquely identify this contentprovider, external callers can find it based on this identity. Recommended for the company domain name, keep uniqueness
③ path: Can be used to represent the data we want to manipulate, and the path should be built according to the business:

To manipulate records with ID 10 in the person table
Content://cn.xycompany.providers.personprovider/person/10

To manipulate the name field of a record with ID 10 in the person table
Content://cn.xycompany.providers.personprovider/person/10/name

To manipulate all records in the person table
Content://cn.xycompany.providers.personprovider/person

The data you want to manipulate does not necessarily come from a database, or it can be stored in a file, such as the name node under the user node in the XML file.

Content://cn.xycompany.providers.personprovider/person/10/name

To convert a string to a URI, you can use the parse () method in the URI class
Uri uri = uri.parse ("Content://cn.xycompany.providers.personprovider/person")

Iii. Introduction to Urimatcher, Contenturis and Contentresolver

The URI represents the data to manipulate, so it is often necessary to parse the URI and fetch the data from the URI. The Android system provides two tool classes for manipulating URIs, Urimatcher and Contenturis, respectively. Mastering their use will facilitate our development efforts.

Urimatcher

Used to match URIs

① the need to match the URI path to all registered

The constant Urimatcher.no_match represents a return code (-1) that does not match any path.
Urimatcher urimatcher = new Urimatcher (urimatcher.no_match);

If the match () method matches the Content://cn.xycompany.providers.personprovider/person path, the match code of 1 is returned.
Urimatcher.adduri ("Content://cn.xycompany.providers.personprovider", "person", 1);

If the match () method matches the CONTENT://CN.XYCOMPANY.PROVIDERS.PERSONPROVIDER/PERSON/10 path, the match code of 2 is returned.
Urimatcher.adduri ("Content://cn.xycompany.providers.personprovider", "person/#", 1);

② you have registered a URI that needs to be matched, you can use the Urimatcher.match (URI) method to match the input URI

Contenturis
Contenturis is an action class for URIs, where the Withappendedid (URI, id) is used to add the ID portion of the path, and the Parseid (URI) method is useful for getting the ID part of the path.
Uri Inserturi = Uri.parse ("Content://cn.xycompany.providers.personprovider/person" + ID), equivalent to
Uri Inserturi = Contenturis.withappendedid (URI, id);

Contentresolver
When external applications need to add, delete, modify, and query the data in ContentProvider, you can use the Contentresolver class to do so. To get the Contentresolver object, you can use the Getcontentresolver () method provided by the activity. Contentresolver uses the INSERT, delete, update, and query methods to manipulate the data.
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

ContentProvider customization and content providers for SMS and contacts

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.