Android 14th-content provider (ContentProvider) and contentprovider
Android 14th-content provider ContentProvider-content provider 1. Introduction to ContentProvider
ContentProvider is a method or standard API for data exchange between different applications.
- ContentProvider provides external data in a certain Uri, allowing other applications to access or modify data
- Other programs access the specified data according to the Uri.
2. Uri Introduction
Http://www.qq.com: 80/news. jsp
- Http: //: The Protocol Part of the URL, as long as the network is accessed through the HTTP protocol, this part is fixed.
- Www.qq.com: domain name Section
- News. jsp: website resources. resources that cannot be accessed are different. This part is dynamic.
Required by ContentProvider; Uri is similar to the above
content://com.pc.pp.provider/words
- Content: // specified by ContentProvider of Android, just like the default http: //, the default ContentProvider protocol is Content ://
- Com. pc. pp. provider: This part is the authorities of ContentProvider. The system uses this part to find the ContentProvider to operate on. As long as the specified ContentProvider is accessed, this part is fixed.
- Words: Resource part or data
3. Create ContentProvider
Create a data help class
public class BankSqliteOpenHelper extends SQLiteOpenHelper { public BankSqliteOpenHelper(Context context) { super(context, "bank.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { String sql = "create table account(_id integer primary key, name varchar(30),money double)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }}
Create a ContentProvider
/** Content provider of the local database, @ author Liu Nan * 2016-3-2 8:35:19 */public class BankDbProvider extends ContentProvider {private static final String TAG = "BankDbProvider "; private static final int ACCOUNT = 0; private static final int ACCOUNT_ID = 1; // default match. If no match exists, UriMatcher is executed. NO_MATCHprivate static UriMatcher matcher = new UriMatcher (UriMatcher. NO_MATCH); // database operation class private BankSqliteOpenHelper helper;/*** initialize some matching Uris */ Static {matcher. addURI ("com. itheima. bankdb. bankDbProvider "," account ", ACCOUNT); matcher. addURI ("com. itheima. bankdb. bankDbProvider "," account/# ", ACCOUNT_ID);}/*** when this Provider is created, perform some initial operations */@ Overridepublic boolean onCreate () {helper = new BankSqliteOpenHelper (getContext (); return true;}/*** query operation */@ Overridepublic Cursor query (Uri uri, String [] projection, String selection, string [] selecti OnArgs, String sortOrder) {if (matcher. match (uri) = ACCOUNT) {SQLiteDatabase db = helper. getReadableDatabase (); Cursor cursor = db. query ("account", projection, selection, selectionArgs, null, null, sortOrder); return cursor;} else if (matcher. match (uri) = ACCOUNT_ID) {SQLiteDatabase db = helper. getReadableDatabase (); long id = ContentUris. parseId (uri); Cursor cursor = db. query ("account", nul L, "_ id =? ", New String [] {id +" "}, null, null, sortOrder); return cursor;} return null;}/*** return type, mainly for query operations * vnd. android. cursor. dir: returns multiple data records * vnd. android. cursor. item: returns a piece of data */@ Overridepublic String getType (Uri uri) {if (matcher. match (uri) = ACCOUNT) {return "vnd. android. cursor. dir/account ";} else if (matcher. match (uri) = ACCOUNT_ID) {return "vnd. android. cursor. item/account ";} return null;}/*** insert operation */@ Overridepublic Uri insert (Uri uri, ContentValues values) {if (matcher. match (uri) = ACCOUNT) {SQLiteDatabase db = helper. getWritableDatabase (); long insert = db. insert ("account", null, values); db. close ();} return uri;}/*** delete operation */@ Overridepublic int delete (Uri uri, String selection, String [] selectionArgs) {if (matcher. match (uri) = ACCOUNT) {SQLiteDatabase db = helper. getWritableDatabase (); int delete = db. delete ("account", selection, selectionArgs); db. close (); return delete;} return 0;}/*** update operation */@ Overridepublic int update (Uri uri, ContentValues values, String selection, String [] selectionArgs) {if (matcher. match (uri) = ACCOUNT) {SQLiteDatabase db = helper. getWritableDatabase (); int update = db. update ("account", values, selection, selectionArgs); db. close (); return update;} return 0 ;}}
Register this provider in the inventory file
<! -- Register Provider authorities: access path exposed externally --> <provider android: name = "com. itheima. bankdb. provider. bankDbProvider "android: authorities =" com. itheima. bankdb. bankDbProvider "> </provider>
Authorities: You can define a package name. Provider.
4. Access the Provider of this application
Create an application
ContentResolver resolver = getContentResolver (); Use this object to parse the object Privoider
/*** Insert data ** @ param v */public void insert (View v) {ContentResolver resolver = getContentResolver (); Uri uri = Uri. parse ("content: // com. itheima. bankdb. bankDbProvider/account "); ContentValues values = new ContentValues (); values. put ("name", "lisi"); values. put ("money", 503.3); Uri insert = resolver. insert (uri, values); System. out. println ("insert:" + insert);}/*** update ** @ param v */public void upda Te (View v) {ContentResolver resolver = getContentResolver (); Uri uri = Uri. parse ("content: // com. itheima. bankdb. bankDbProvider/account "); ContentValues values = new ContentValues (); values. put ("money", 1003.3); int update = resolver. update (uri, values, "name =? ", New String [] {" lisi "}); System. out. println ("update" + update);}/*** delete ** @ param v */public void delete (View v) {ContentResolver resolver = getContentResolver (); uri uri = Uri. parse ("content: // com. itheima. bankdb. bankDbProvider/account "); int delete = resolver. delete (uri, "name =? ", New String [] {" lisi "}); System. out. println ("delete:" + delete);}/*** query all ** @ param v */public void query (View v) {ContentResolver resolver = getContentResolver (); uri uri = Uri. parse ("content: // com. itheima. bankdb. bankDbProvider/account "); Cursor cursor = resolver. query (uri, null, null); while (cursor. moveToNext () {int id = cursor. getInt (cursor. getColumnIndex ("_ id"); String name = cursor. getString (cursor. getColumnIndex ("name"); double money = cursor. getDouble (cursor. getColumnIndex ("money"); Toast. makeText (this, "ID:" + id + "name:" + name + ", Money:" + money, Toast. LENGTH_SHORT ). show ();} cursor. close ();}/*** query a ** @ param v */public void queryOne (View v) {ContentResolver resolver = getContentResolver (); Uri uri = Uri. parse ("content: // com. itheima. bankdb. bankDbProvider/account/2 "); Cursor cursor = resolver. query (uri, null, null); while (cursor. moveToNext () {int id = cursor. getInt (cursor. getColumnIndex ("_ id"); String name = cursor. getString (cursor. getColumnIndex ("name"); double money = cursor. getDouble (cursor. getColumnIndex ("money"); Toast. makeText (this, "ID:" + id + "name:" + name + ", Money:" + money, Toast. LENGTH_SHORT ). show ();} cursor. close ();}
5. content providers using text messages
Add a piece of data to the text message
/*** Add a data record to the text message * @ param v */public void insert (View v) {// retrieve the content for parsing ContentResolver resolver = getContentResolver (); // view the provided uri Uri uri = Uri in the source code. parse ("content: // sms"); // The data to be added is a MAP set, and the field ContentValues values = new ContentValues (); values. put ("address", "10086"); values. put ("date", System. currentTimeMillis (); values. put ("body", "This is a new text message"); values. put ("type", 1); resolver. insert (uri, values );}
Add permission
<uses-permission android:name="android.permission.READ_SMS"/> <uses-permission android:name="android.permission.WRITE_SMS"/>
6. Use the contact ContentProvider
Query contacts
/*** Query all contacts, * @ param context * @ return */public static List <ContactInfo> getContacts (Context context) {List <ContactInfo> list = new ArrayList <ContactInfo> (); Uri rowUri = Uri. parse ("content: // com. android. contacts/raw_contacts "); Uri dataUri = Uri. parse ("content: // com. android. contacts/data "); ContentResolver resolver = context. getContentResolver (); Cursor rawCursor = resolver. query (rowUri, new St Ring [] {"contact_id"}, null); while (rawCursor. moveToNext () {String id = rawCursor. getString (rawCursor. getColumnIndex ("contact_id"); if (id = null) {continue;} ContactInfo info = new ContactInfo (); info. id = id; Cursor dataCursor = resolver. query (dataUri, new String [] {"data1", "mimetype"}, "raw_contact_id =? ", New String [] {id}, null); while (dataCursor. moveToNext () {String data1 = dataCursor. getString (dataCursor. getColumnIndex ("data1"); String mimetype = dataCursor. getString (dataCursor. getColumnIndex ("mimetype"); if ("vnd. android. cursor. item/email_v2 ". equals (mimetype) {info. email = data1;} else if ("vnd. android. cursor. item/im ". equals (mimetype) {info. im = data1;} else if ("vnd. android. cursor. item/phone_v2 ". equals (mimetype) {info. phone = data1;} else if ("vnd. android. cursor. item/name ". equals (mimetype) {info. name = data1 ;}} dataCursor. close (); list. add (info);} rawCursor. close (); return list ;}
Add contact
/*** Add contact ** @ param v */public void insert (View v) {String name = etName. getText (). toString (). trim (); String phone = etPhone. getText (). toString (). trim (); String email = etEmail. getText (). toString (). trim (); if (TextUtils. isEmpty (name) | TextUtils. isEmpty (phone) | TextUtils. isEmpty (email) {Toast. makeText (this, "name, phone number, email cannot be blank", Toast. LENGTH_SHORT ). show (); return;} Uri rowUri = Uri. parse ("content: // com. android. contacts/raw_contacts "); Uri dataUri = Uri. parse ("content: // com. android. contacts/data "); // first query ID ContentResolver resolver = getContentResolver (); Cursor rawCursor = resolver. query (rowUri, new String [] {"_ id"}, null); rawCursor. moveToLast (); int id = 1; id = rawCursor. getInt (rawCursor. getColumnIndex ("_ id") + 1; rawCursor. close (); // insert raw_contact table ID ContentValues values = new ContentValues (); values. put ("contact_id", id); resolver. insert (rowUri, values); // insert data into the data table ContentValues nameValues = new ContentValues (); nameValues. put ("data1", name); nameValues. put ("mimetype", "vnd. android. cursor. item/name "); nameValues. put ("raw_contact_id", id); resolver. insert (dataUri, nameValues); ContentValues phoneValues = new ContentValues (); phoneValues. put ("data1", phone); phoneValues. put ("mimetype", "vnd. android. cursor. item/phone_v2 "); phoneValues. put ("raw_contact_id", id); resolver. insert (dataUri, phoneValues); ContentValues emailValues = new ContentValues (); emailValues. put ("data1", email); emailValues. put ("mimetype", "vnd. android. cursor. item/email_v2 "); emailValues. put ("raw_contact_id", id); resolver. insert (dataUri, emailValues); Toast. makeText (this, "added successfully", Toast. LENGTH_SHORT ). show ();}
Add permission
<uses-permission android:name="android.permission.READ_CONTACTS"/><uses-permission android:name="android.permission.WRITE_CONTACTS"/>
7. Content observer
The ContentObserver observes the data of a specified path. Once the data changes, it will receive a notification.
Purpose: When the database data changes, a notification will be issued. After receiving the notification, We can query the database to obtain the latest data.
Release notification
// Parameter 1: the location where the data has changed // parameter 2: The content observer object. If it is null, it indicates that no specific person is told, getContext (). getContentResolver (). notifyChange (uri, null );
Receive notification
// Register the content observer Uri uri = Uri. parse ("content: // com. itheima. bank. BACKDOOR/account "); // parameter 1: the specific position of the observation. uri // parameter 2: true: the uri can be notified if it matches the first half. false. all letters match to receive the notification getContentResolver (). registerContentObserver (uri, true, new MyObserver (new Handler (); -------------------- class MyObserver extends ContentObserver {public MyObserver (Handler handler) {super (handler );} @ Override public void onChange (boolean selfChange) {super. onChange (selfChange); Log. d (TAG, "table data has changed .. ");}}