Android component ContentProvider

Source: Internet
Author: User

Android component ContentProvider

Android component ContentProvider

Android data storage supports five methods: Shared Preferences, network storage, file storage, external storage, and SQLite. Generally, these storage methods only share data in a single application, sometimes we need to operate some data of other applications, such as the address book, text message, and photos in common systems. Therefore, cloud storage, address book, and photo exposure are born. ContentProvider can be understood as a content provider or an interface. It provides an interface for external access and sometimes requires permission control.

ContentProvider Introduction

ContentProvider provides us with a mechanism to share data before an application, and we know that every application runs in different applications, data sharing between different programs is a realistic need, and the program cannot keep a closed loop. The advantage of sharing data outside ContentProvider in Android is that data access is unified. Summary:

ContentProvider provides a unified interface for data storage and retrieval. ContentProvide encapsulates data without worrying about the details of data storage. Organize data in the form of tables. You can use ContentProvider to share data between different applications. Android provides default ContentProvider (including audio, video, image, and address book) for common data ).

Speaking of the advantages of ContentProvider, You can't end with Uri (Universal Resource Identifier). Note that it is not a URL or a common Resource Identifier. You can simply read the contact's Uri, content: // contacts/people,

Content: // It is a fixed prefix. The contacts Host Name (or Authority) is used to uniquely identify the ContentProvider. External callers can call the ContentProvider according to the identity. The people path (path) indicates the data to be operated. The path construction depends on the business; custom ContentProvider

As the saying goes, if you want to do something better, you must first sharpen the tool. If you want to become a content provider, you must first have data and create a SqlDbConncetion:

View sourceprint? 01. public class SqlDBConnection extends SQLiteOpenHelper { 02. 03. private static final String DbName = "Book.db" ; 04. private static int version= 1 ; 05. 06. public SqlDBConnection(Context context) { 07. super (context, DbName, null , version); 08. } 09. 10. @Override 11. public void onCreate(SQLiteDatabase db) { 12. // TODO Auto-generated method stub 13. String sqlString= "create table Book (id integer primary key autoincrement,Name nvarchar(200),Title nvarchar(200))" ; 14. db.execSQL(sqlString); 15. } 16. 17. @Override 18. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 19. // TODO Auto-generated method stub 20. } 21. }

In the junit test described in the previous article, you can use the following data for initialization:

View sourceprint? 01. public class BookCase extends AndroidTestCase { 02. 03. public void Intial() { 04. SqlDBConnection dbConnection = new SqlDBConnection(getContext()); 05. SQLiteDatabase sqlDataBase = dbConnection.getWritableDatabase(); 06. long row = 0 ; 07. for ( int i = 0 ; i < 5 ; i++) { 08. ContentValues values = new ContentValues(); 09. values.put( "Name" , "Books" +i); 10. values.put( "Title" , "Title" + i); 11. row = sqlDataBase.insert( "Book" , null , values); 12. Log.i( "BookCase" , "Inserted successfully :" + row); 13. } 14. } 15. }

The first step is the basic work. In this case, you can create your own ContentProvider:

Expand source

The host name must be configured by yourself in the AndroidManifest. xml file. The host name must be unique. It is best to use the package name:

View sourceprint? 1. "com.example.googlecontentprovider.MyContentProvider" 2. android:authorities= "com.example.googlecontentprovider.MyContentProvider" >

If you think the above Code is not very easy to understand, I will explain it separately during the next call.

Use of ContentResolver

It is normal to write the method in an application. The method used to call the program in another program is similar to the interface. Next, let's first look at the original initialized data:

Create a new Android test project and define it as BookCase. First, insert data and define a Uri. The host name is the package name defined above. book/insert corresponds to CONTENT_INSERT:

View sourceprint?01.public void bookInsert() { 02.Uri uri = Uri 03..parse("content://com.example.googlecontentprovider.MyContentProvider/book/insert"); 04.ContentResolver resolver = getContext().getContentResolver(); 05.ContentValues values = new ContentValues(); 06.values.put("Name", "Books 5"); 07.values.put("Title", "Title 5"); 08.uri = resolver.insert(uri, values); 09.Log.i("BookCase", "Uri" + uri); 10.long id = ContentUris.parseId(uri); 11.Log.i("BookCase", "Test successful" + id); 12.}

The result is as follows:

Then update the inserted data, assign values to the Uri with the same Code, initialize a ContentResolver, and call the update method:

View sourceprint?01.public void bookUpdate() { 02.Uri uri = Uri 03..parse("content://com.example.googlecontentprovider.MyContentProvider/book/update"); 04.ContentResolver resolver = getContext().getContentResolver(); 05.ContentValues values=new ContentValues(); 06.values.put("Name", "Modify"); 07.int count = resolver.update(uri, values, " id=?",new String[]{"10"}); 08.Log.i("BookCase", "Updated" + count + "Line"); 09.}

The result is as follows:

Delete the inserted data:

View sourceprint?01.public void bookDelete() { 02.Uri uri = Uri 03..parse("content://com.example.googlecontentprovider.MyContentProvider/book/delete"); 04.ContentResolver resolver = getContext().getContentResolver(); 05.String where =" id=?"; 06.String[] argString = {"10"}; 07.int count = resolver.delete(uri, where, argString); 08.Log.i("BookCase", "Deleted" + count + "Line"); 09.}

The result is as follows:

Query all data:

view sourceprint? 01.public void bookQuery() { 02.Uri uri = Uri 03..parse("content://com.example.googlecontentprovider.MyContentProvider/book/query"); 04.ContentResolver resolver = getContext().getContentResolver(); 05.Cursor cursor=resolver.query(uri, new String[]{"id","Name","Title"}, null, null, null); 06.if (cursor.getCount()>0) { 07.while (cursor.moveToNext()) { 08.int id=cursor.getInt(cursor.getColumnIndex("Id")); 09.String nameString=cursor.getString(cursor.getColumnIndex("Name")); 10.String titleString=cursor.getString(cursor.getColumnIndex("Title")); 11.Log.i("BookCase", id+"---"+nameString+"---"+titleString); 12.} 13.} 14. 15.}

Log records:

Query a single record:

view sourceprint? 01.public void bookQuerySingle() { 02.Uri uri = Uri 03..parse("content://com.example.googlecontentprovider.MyContentProvider/book/query"); 04.ContentResolver resolver = getContext().getContentResolver(); 05.uri=ContentUris.withAppendedId(uri,1); 06.Cursor cursor=resolver.query(uri, new String[]{"id","Name","Title"}, null, null, null); 07.if (cursor.getCount()>0) { 08.while (cursor.moveToNext()) { 09.int id=cursor.getInt(cursor.getColumnIndex("Id")); 10.String nameString=cursor.getString(cursor.getColumnIndex("Name")); 11.String titleString=cursor.getString(cursor.getColumnIndex("Title")); 12.Log.i("BookCase", id+"---"+nameString+"---"+titleString); 13.} 14.} 15.}

Result:

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.