Content Providers Summary

Source: Internet
Author: User

The article is transferred from http://www.cnblogs.com/chenglong/articles/1892029.html. It is a good combination and worth learning.

1. Introduction to contentprovider

When an application inherits the contentprovider class and overwrites the class to provide and store data, it can share its data with other applications. Although data can be shared externally by using other methods, the data access method varies depending on the data storage method. For example, if data is shared externally by using the file method, you need to perform file operations to read and write data; sharedpreferences is used to share data. You must use the sharedpreferencesapi to read and write data. The advantage of using contentprovider to share data is to unify the data access mode.
II. Introduction to the URI class
Uri indicates the data to be operated. Uri contains two parts: 1. contentprovider, 2. a URI consists of the following parts:

1. scheme: the content provider's scheme has been defined by android as: Content ://.
2. Host Name (or authority): Used to uniquely identify the contentprovider, which can be found by external callers.
3. Path: it can be used to represent the data to be operated. The path construction should be based on the business, as shown below:
• To operate records with the ID of 10 in the contact table, you can build the following path:/contact/10.
• The name field of the record with the ID of 10 in the contact table, contact/10/Name
• To operate all records in the contact table, you can build the following path:/contact
The data to be operated may not necessarily come from the database or be stored in files, as follows:
To operate the Name node under the contact node in the XML file, you can build the path:/contact/Name
To convert a string to a URI, you can use the parse () method in the URI class as follows:
Uri uri = URI. parse ("content: // com. Changcheng. provider. contactprovider/contact ")
3. Introduction to urimatcher, contenturist, and contentresolver
Because URI represents the data to be operated, we often need to parse the URI and obtain data from the URI. The Android system provides two tool classes for Uri operations: urimatcher and contenturis. Understanding their usage will facilitate our development work.

Urimatcher: Used to match a URI. Its usage is as follows:
1. First, you need to match all the URI paths to the registration, as shown below:
// Constant urimatcher. no_match indicates the return code (-1) that does not match any path ).
Urimatcher = new urimatcher (urimatcher. no_match );
// If the match () method matches the content: // com. Changcheng. SQLite. provider. contactprovider/contact path, 1 is returned.
Urimatcher. adduri ("com. Changcheng. SQLite. provider. contactprovider", "contact", 1); // Add a URI that needs to be matched. If yes, a matching code is returned.
// If the match () method matches the content: // com. Changcheng. SQLite. provider. contactprovider/contact/230 path, the matching code is 2.
Urimatcher. adduri ("com. Changcheng. SQLite. provider. contactprovider", "contact/#", 2); // # It is a wildcard

2. after registering the URI to be matched, you can use urimatcher. the match (URI) method matches the input URI. If it matches, the matching code is returned. The matching code is the third parameter passed in by calling the adduri () method. Assume that it matches the content: // COM. changcheng. SQLite. provider. contactprovider/contact path. The returned matching code is 1.

Contenturis: used to obtain the ID part after the URI path. It has two practical methods:
• Withappendedid (Uri, ID) is used to add the ID part to the path.
• The parseid (URI) method is used to obtain the ID part from the path.

Contentresolver: When an external application needs to add, delete, modify, and query data in contentprovider, you can use the contentresolver class to obtain the contentresolver object, you can use the getcontentresolver () method provided by activity. Contentresolver uses insert, delete, update, and query methods to operate data.
Iv. contentprovider sample program

Code in manifest. xml:

<application android:icon="@drawable/icon" android:label="@string/app_name">                <activity android:name=".TestWebviewDemo" android:label="@string/app_name">                        <intent-filter>                                <action android:name="android.intent.action.MAIN" />                                <category android:name="android.intent.category.LAUNCHER" />                        </intent-filter>                        <intent-filter>                                <data android:mimeType="vnd.android.cursor.dir/vnd.ruixin.login" />                        </intent-filter>                        <intent-filter>                                <data android:mimeType="vnd.android.cursor.item/vnd.ruixin.login" />                        </intent-filter>                                         </activity>                <provider android:name="MyProvider" android:authorities="com.ruixin.login" />        </application>

You must register for the provider in <Application> </Application> !!!!
First, define a database tool class:

public class RuiXin {         public static final String DBNAME = "ruixinonlinedb";        public static final String TNAME = "ruixinonline";        public static final int VERSION = 3;                 public static String TID = "tid";        public static final String EMAIL = "email";        public static final String USERNAME = "username";        public static final String DATE = "date";        public static final String SEX = "sex";                          public static final String AUTOHORITY = "com.ruixin.login";        public static final int ITEM = 1;        public static final int ITEM_ID = 2;                 public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ruixin.login";        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ruixin.login";                 public static final Uri CONTENT_URI = Uri.parse("content://" + AUTOHORITY + "/ruixinonline");}

Then create a database

public class DBlite extends SQLiteOpenHelper {        public DBlite(Context context) {                super(context, RuiXin.DBNAME, null, RuiXin.VERSION);                // TODO Auto-generated constructor stub        }        @Override        public void onCreate(SQLiteDatabase db) {                // TODO Auto-generated method stub                        db.execSQL("create table "+RuiXin.TNAME+"(" +                                RuiXin.TID+" integer primary key autoincrement not null,"+                                RuiXin.EMAIL+" text not null," +                                RuiXin.USERNAME+" text not null," +                                RuiXin.DATE+" interger not null,"+                                RuiXin.SEX+" text not null);");        }        @Override        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {                // TODO Auto-generated method stub        }        public void add(String email,String username,String date,String sex){                SQLiteDatabase db = getWritableDatabase();                ContentValues values = new ContentValues();                values.put(RuiXin.EMAIL, email);                values.put(RuiXin.USERNAME, username);                values.put(RuiXin.DATE, date);                values.put(RuiXin.SEX, sex);                db.insert(RuiXin.TNAME,"",values);        }}

Create a myprovider. Java package the database interface:

public class MyProvider extends ContentProvider{         DBlite dBlite;        SQLiteDatabase db;                 private static final UriMatcher sMatcher;        static{                sMatcher = new UriMatcher(UriMatcher.NO_MATCH);                sMatcher.addURI(RuiXin.AUTOHORITY,RuiXin.TNAME, RuiXin.ITEM);                sMatcher.addURI(RuiXin.AUTOHORITY, RuiXin.TNAME+"/#", RuiXin.ITEM_ID);         }        @Override        public int delete(Uri uri, String selection, String[] selectionArgs) {                // TODO Auto-generated method stub                db = dBlite.getWritableDatabase();                int count = 0;                switch (sMatcher.match(uri)) {                case RuiXin.ITEM:                        count = db.delete(RuiXin.TNAME,selection, selectionArgs);                        break;                case RuiXin.ITEM_ID:                        String id = uri.getPathSegments().get(1);                        count = db.delete(RuiXin.TID, RuiXin.TID+"="+id+(!TextUtils.isEmpty(RuiXin.TID="?")?"AND("+selection+')':""), selectionArgs);                    break;                default:                        throw new IllegalArgumentException("Unknown URI"+uri);                }                getContext().getContentResolver().notifyChange(uri, null);                return count;        }         @Override        public String getType(Uri uri) {                // TODO Auto-generated method stub                switch (sMatcher.match(uri)) {                case RuiXin.ITEM:                        return RuiXin.CONTENT_TYPE;                case RuiXin.ITEM_ID:                    return RuiXin.CONTENT_ITEM_TYPE;                default:                        throw new IllegalArgumentException("Unknown URI"+uri);                }        }         @Override        public Uri insert(Uri uri, ContentValues values) {                // TODO Auto-generated method stub                                 db = dBlite.getWritableDatabase();                long rowId;                if(sMatcher.match(uri)!=RuiXin.ITEM){                        throw new IllegalArgumentException("Unknown URI"+uri);                }                rowId = db.insert(RuiXin.TNAME,RuiXin.TID,values);                   if(rowId>0){                           Uri noteUri=ContentUris.withAppendedId(RuiXin.CONTENT_URI, rowId);                           getContext().getContentResolver().notifyChange(noteUri, null);                           return noteUri;                   }                   throw new IllegalArgumentException("Unknown URI"+uri);        }         @Override        public boolean onCreate() {                // TODO Auto-generated method stub                this.dBlite = new DBlite(this.getContext());//                db = dBlite.getWritableDatabase();//                return (db == null)?false:true;                return true;        }         @Override        public Cursor query(Uri uri, String[] projection, String selection,                        String[] selectionArgs, String sortOrder) {                // TODO Auto-generated method stub                db = dBlite.getWritableDatabase();                               Cursor c;                Log.d("-------", String.valueOf(sMatcher.match(uri)));                switch (sMatcher.match(uri)) {                case RuiXin.ITEM:                        c = db.query(RuiXin.TNAME, projection, selection, selectionArgs, null, null, null);                                         break;                case RuiXin.ITEM_ID:                        String id = uri.getPathSegments().get(1);                        c = db.query(RuiXin.TNAME, projection, RuiXin.TID+"="+id+(!TextUtils.isEmpty(selection)?"AND("+selection+')':""),selectionArgs, null, null, sortOrder);                    break;                default:                        Log.d("!!!!!!", "Unknown URI"+uri);                        throw new IllegalArgumentException("Unknown URI"+uri);                }                c.setNotificationUri(getContext().getContentResolver(), uri);                return c;        }        @Override        public int update(Uri uri, ContentValues values, String selection,                        String[] selectionArgs) {                // TODO Auto-generated method stub                return 0;        }}

Finally, create a test class:

Public class test extends activity {/** called when the activity is first created. */private dblite dblite1 = new dblite (this); private contentresolver; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // Add dblite1.add (email, username, date, sex) to the database first; // use contentresolver to find contentresolver = testwebviewdemo. this. getcontentresolver (); cursor = contentresolver. query (ruixin. content_uri, new string [] {ruixin. email, ruixin. username, ruixin. date, ruixin. sex}, null); While (cursor. movetonext () {toast. maketext (testwebviewdemo. this, cursor. getstring (cursor. getcolumnindex (ruixin. email) + "" + cursor. getstring (cursor. getcolumnindex (ruixin. username) + "" + cursor. getstring (cursor. getcolumnindex (ruixin. date) + "" + cursor. getstring (cursor. getcolumnindex (ruixin. sex), toast. length_short ). show () ;}startmanagingcursor (cursor); // close the cursor after searching }}

Note: The above is a test in a program, you can also create a new project to simulate a new program, and then add the code queried above to the new program! This simulates the data sharing Function of contentprovider!

Create a project: testprovider

Create a test activity

Public class test extends activity {/** called when the activity is first created. */private contentresolver; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // use contentresolver to find contentresolver = testwebviewdemo. this. getcontentresolver (); cursor = contentresolver. query (ruixin. content_uri, new string [] {ruixin. email, ruixin. username, ruixin. date, ruixin. sex}, null); While (cursor. movetonext () {toast. maketext (testwebviewdemo. this, cursor. getstring (cursor. getcolumnindex (ruixin. email) + "" + cursor. getstring (cursor. getcolumnindex (ruixin. username) + "" + cursor. getstring (cursor. getcolumnindex (ruixin. date) + "" + cursor. getstring (cursor. getcolumnindex (ruixin. sex), toast. length_short ). show () ;}startmanagingcursor (cursor); // close the cursor after searching }}

Run this program to query shared data!

Note: you do not need to register the provider in manifest. xml of the newly created program. Just run it directly; otherwise, an error is reported!

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.