a brief description of content provider (sdk doc translation)

2011-05-24  来源:本站原创  分类:Mobile  人气:142 

Content provider Content provider is used to read and store data, use our own data can be shared with others, while other data can be read to allow the case in others. He is the only one can be shared between different applications of data, no public storage area, all applications can access the android.

android system comes with some of the content provider for the common data types, such as music, video, pictures, contact information, etc., you can view these stuff android.provider package, you can query the content providers the data they contain (But you have to get permission from other user programs).

If you want your data can get others to share, you have to do two operations, 1. You need to build your own contentProvider (a system of contentProvider subclasses) to store data, 2. You go through the others to provide the provider store their data (the provider must be you need to manipulate the data types, and you have the right to write this provider).

contentprovider basis

What a contentprovider store data, developers have full control of him, but all contentprovider must implement the same interface used to query and return results, such as adding data, modify, and delete.

Users can provide an interface through the system back contentResolver getContentResolver objects (call this object in the activity), when you get this object,
The general method used in the activity for the
ContentResolver c = getContentResolver (); this time and provide contentprovider you can interact with the application,
When we launched the event of a query, the query system identification contentProvider provided by uri, and then determine the contentprovider up and running, android, when the system starts to initialize all the contentprovider objects (their own needs in the manifest provided contentprovider file a statement of the specific approach for a talk)
The application of some public to realize you never need to own (the benefits of open source software, effort, money, support open source, but also reduces the level of our programmers), in fact, you do not have a direct and an contentprovider deal (unless it is their own), android system is not a contentprovider provides an instance (singleton), but it can deal with multiple contentresolver (thread safe), thread safety is completed by the contentresolver and contentprovider, we use who better than to worry about.

Data model

contentprovider table is open in accordance with their own data. Each row is a record, each column is a concrete value, for example here is not, and do not know if even the table, I suggest you still do not exist in software development, and avoid reducing the level programmer, Oh, off topic

In the android's in each row must contain one column, the column named "_id", he is the primary key. The concept and role of the primary key reference book databases

Each query returns a Cursor object, did oracle pl / sql programming may be that what he meant. cursor objects allow us to move from one line to another line, one column to another column, you can easily read the data. He also provides a specific type of data reading methods, such as getString, getInteger other methods, provided that you must know the type of each field represents. (I will detail the results and the cursor query object)

uri is the role of accurate positioning contentprovider we need the data provided, otherwise laissez-faire (unsafe, have to take), each contentprovider provide an open uri, he can accurately identify a data set, a contentprovider control multiple data sets can be accurately identified by uri them, in each data set. All of the uri must be content: / / at the beginning, content: as a recognition contentprovider identity.

If you define a contentprovider, then you also need him to develop a uri, simplifying the work of others to call and make future updates cleaner (please explain heroes), android defined content_uri constant and platform for all of the interactive provider (Android defines CONTENT_URI constants for all the providers that come with the platform). For example, the query name and contact links pictures of the uri is:
android.provider.Contacts.Phones.COntent_URI and android.provider.Contacts.Photos.CONTENT_URI.
uri and contentprovider interaction for all users. Approach each contentresolver the first argument is the uri, he will be and which defines the contentresolver contentprovider dialogue, and which will be on the table.

Query a contentprovider

You need three steps to query a contentprovidr

1.contentprovidr uri defined
2. You need to return the table column name
3. These data types (I am a little bit of doubt)

If you want to query a specific data section, you need to develop ID

Generate queries

You can query the object ContentResolver method or Activity.managedQuery method, the parameters are the same, returns a cursor object, but the method allows activity managedQuery cursor object life cycle management, he can do many things, for example, when the activity pauses after the object will automatically close the cursor. When the activity restart when it can automatically go to re-query. You can also call activit of startmanagingCursor (Cursor c) ways to manage this object.

query methods and managedQuery method for the provider of the first argument uri, on the uri has been introduced above,

android system provides a number of helper methods, such as, COntentUris.withAppendedId () and Uri.withAppendedPath () method, they can easily add one for uri id, two methods are static, return a uri object, the following is android help documentation provided in the examples

import android.provider.Contacts.People;
import android.content.ContentUris;
import android.net.Uri;
import android.database.Cursor;

/ / Use the ContentUris method to produce the base URI for the contact with _ID == 23.
/ / Uri myPerson = ContentUris.withAppendedId (People.CONTENT_URI, 23);

/ / Alternatively, use the Uri method to produce the base URI.
/ / It takes a string rather than an integer.
Uri myPerson = Uri.withAppendedPath (People.CONTENT_URI, "23");

/ / Then query for this specific record:
Cursor cur = managedQuery (myPerson, null, null, null, null);

query () and managedQuery () method parameters represent the meaning of the following:

Parameter 1: uri. Parameter 2: The need to return the column names, such as _id, number, nember_key so, if it is empty, it returns all columns. Parameter 3: the equivalent of sql statement where conditions, such as "_id" = 12, "_id" =?. If the time is null, return all the columns, provided that you return the entire uri is uri. Parameter 4: If the election form is included in 3 "_id" =? The conditions, then this can not be empty. If this is empty, the purpose is to provide query speed, so that the soft parse sql statement. Parameter 5: a sort, for example to sort by id, for the "id desc", do not need to add order by. For details, see android api android.content.contentResolver

The data returned by the query

Each query will return o one or more records. Does not return null, and each line will contain _id this column,

Read the returned data

Read data from the cursor when the data must know the type, but you can also getString method, read all the data, but the returned objects are of type string, in your practice, you still want to convert to real type, so the first time to use the method to get the object, you can use the index or column name to read the data. Does not seem to provide a direct reading of the data using the method of column names, do not know why, to be solved (is it I did not notice.)
As follows:
if (cur.moveToFirst ()) {

String name;
String phoneNumber;
int nameColumn = cur.getColumnIndex (People.NAME);
int phoneColumn = cur.getColumnIndex (People.NUMBER);
String imagePath;

do {
/ / Get the field values
name = cur.getString (nameColumn);
phoneNumber = cur.getString (phoneColumn);

/ / Do something with the values.

} While (cur.moveToNext ());


If a query returns the binary data, such as image or music. Then there is the table data can also be linked via a uri to the appropriate content. Using uri can get the data. In general, small data, such as 20-50k or smaller, there is a database directly, you can getBlod () method to the btye data. If the table exists in the uri, so you do not need to directly open or read this file, (but have this permission). You should call ContentResolver.onpenInputStream () to get inputStream object, and then can be read.

Modify data

3.batch update

One. The first step in adding data to add data, you need to create a key-value object ContentValues ​​(equivalent to map, to map the internal implementation or realization, android encapsulates the map java objects). Data set, the call contentResolver the insert method can be inserted into the
insert method returns the type id is not our imagination, but a uri object representing the newly inserted record uri. You can use it check the record just added. As follows:
ContentValues ​​values ​​= new ContentValues ​​();

/ / Add Abraham Lincoln to contacts and make him a favorite.
values.put (People.NAME, "Abraham Lincoln");
/ / 1 = the new contact is added to favorites
/ / 0 = the new contact is not added to favorites
values.put (People.STARRED, 1);

Uri uri = getContentResolver (). Insert (People.CONTENT_URI, values);

II. Modify, delete, do not say, basically similar, update and delete methods.

Create a contentprovider

1. Creating a subclass contentProvider
2. Definition uri
3. Used to create the class. Open a SQLiteDatabase object. openRendHelper and openWirterHelper methods.
4. In the manifest file a statement of this class, we must declare, <provider android: name = "com.example.autos.AutoInfoProvider"
android: authorities = "com.example.autos.autoinfoprovider"
... />
</ Provider>

Implementation class, the need to implement the methods of query, insert update getType oncreate
The format of content: / / xxx.xxx.xxx all the data, a piece of data content: / / xxx.xxx.xxx / id
<Provider android: name = "com.example.autos.AutoInfoProvider"
android: authorities = "com.example.autos.autoinfoprovider"
... />
</ Provider>
import java.util.Calendar;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DiaryDbAdapter {

public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_ROWID = "_id";
public static final String KEY_CREATED = "created";

private static final String TAG = "DiaryDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_CREATE = "create table diary (_id integer primary key autoincrement,"
+ "Title text not null, body text not null, created text not null);";

private static final String DATABASE_NAME = "database";
private static final String DATABASE_TABLE = "diary";
private static final int DATABASE_VERSION = 1;

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

DatabaseHelper (Context context) {
super (context, DATABASE_NAME, null, DATABASE_VERSION);

@ Override
public void onCreate (SQLiteDatabase db) {

@ Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL ("DROP TABLE IF EXISTS diary");
onCreate (db);

public DiaryDbAdapter (Context ctx) {
this.mCtx = ctx;

public DiaryDbAdapter open () throws SQLException {
mDbHelper = new DatabaseHelper (mCtx);
mDb = mDbHelper.getWritableDatabase ();
return this;

public void closeclose () {
mDbHelper.close ();

public long createDiary (String title, String body) {
ContentValues ​​initialValues ​​= new ContentValues ​​();
initialValues.put (KEY_TITLE, title);
initialValues.put (KEY_BODY, body);
Calendar calendar = Calendar.getInstance ();
String created = calendar.get (Calendar.YEAR) + "years"
+ Calendar.get (Calendar.MONTH) + "months"
+ Calendar.get (Calendar.DAY_OF_MONTH) + "Day"
+ Calendar.get (Calendar.HOUR_OF_DAY) + "time"
+ Calendar.get (Calendar.MINUTE) + "minutes";
initialValues.put (KEY_CREATED, created);
return mDb.insert (DATABASE_TABLE, null, initialValues);

public boolean deleteDiary (long rowId) {

return mDb.delete (DATABASE_TABLE, KEY_ROWID + "=" + rowId, null)> 0;

public Cursor getAllNotes () {

return mDb.query (DATABASE_TABLE, new String [] {KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_CREATED}, null, null, null, null, null);

public Cursor getDiary (long rowId) throws SQLException {

Cursor mCursor =

mDb.query (true, DATABASE_TABLE, new String [] {KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_CREATED}, KEY_ROWID + "=" + rowId, null, null,
null, null, null);
if (mCursor! = null) {
mCursor.moveToFirst ();
return mCursor;


public boolean updateDiary (long rowId, String title, String body) {
ContentValues ​​args = new ContentValues ​​();
args.put (KEY_TITLE, title);
args.put (KEY_BODY, body);
Calendar calendar = Calendar.getInstance ();
String created = calendar.get (Calendar.YEAR) + "years"
+ Calendar.get (Calendar.MONTH) + "months"
+ Calendar.get (Calendar.DAY_OF_MONTH) + "Day"
+ Calendar.get (Calendar.HOUR_OF_DAY) + "time"
+ Calendar.get (Calendar.MINUTE) + "minutes";
args.put (KEY_CREATED, created);

return mDb.update (DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)> 0;

  • a brief description of content provider (sdk doc translation) 2011-05-24

    Content provider Content provider is used to read and store data, use our own data can be shared with others, while other data can be read to allow the case in others. He is the only one can be shared between different applications of data, no public

  • content provider (Reprinted) 2010-03-29

    Study on Android 【2】 - ContentProvider Data Model Overview [Favorites this page] [Print] Author: 2008-02-25 from ITPUB Forum Content Navigation: Page 1 Page 1: the first one the text Tag: Android Java Android】 【IT168 technical documentation of the da

  • Learning Content Provider 2010-03-29

    1. Is that all the process the only way to share data; 2. With the Content Resolver interact with the Content Provider; 3.Content Provider to provide data model, and in the database table records is very similar; 4. In a custom Content Provider, at l

  • Content Provider based SQL 2010-04-26

    Keywords: content provider, SQL, SQLite This article is a Content Provider's second series, the recent busy (to find their own reasons) did not update the blog, sin ah. No bullshit, that is entered. As the Content Provider's implementation mostly be

  • android Content provider 2010-06-08

    Content provider, for other applications (also providing the Content provider applications) Provides a consistent interface to data storage model. Through this interface, you can easily extract the data you want, Modify or delete will become very eas

  • Example customized Content Provider android 2010-12-09

    We all know the key to their shared data and other applications in two ways: create your own Content Provider (that is inherited from a subclass of Content Provider) or your data is added to the existing Content Provider to go after need to ensure th

  • Android-based: Android Content Provider [change] 2010-03-29

    Android application can use the files or SqlLite database to store data. Content Provider provides a multi-way data sharing between applications, such as: contact information can be multiple applications to access. Content Provider is a realization o

  • Android basis: Android Content Provider [change] 2010-03-17

    Android application can use the file or SqlLite database to store data. Content Provider provides a multi-way data sharing between applications, such as: contact information can be more than one application access. Content Provider is to achieve a se

  • Android content provider base and to use 2010-05-07

    In an article on how to operate andoird mentioned in the database, if you just want to own this application use the database, it is already very good, but, android there is a unique, Shu Juku Zhineng created by its those used by other applications ca

  • Create your own Android content provider 2010-05-07

    In a previous blog , it has to introduce how to use the content provider, if you need to create your own cotent provider, also is the custom own unique, you need to do is very simple, that is derived from the abstract class ContentProvider out of you

  • Content Provider's use of summary 2010-08-18

    Android in the Content provider mechanism can support multiple applications to store and read data. This is also to share data across applications the only way. In the android system, not a public area of memory for multiple applications to share sto

  • Android Content Provider [transfer] 2010-10-21

    Android application can use the file or SqlLite database to store data. Content Provider provides a multi-way data sharing between applications, such as: contact information can be more than one application access. Content Provider is a realization o

  • Using and creating Content Provider 2010-10-30

    Android application can use the file or SqlLite database to store data. Content Provider provides a multi-way data sharing between applications, such as: contact information can be more than one application access. Content Provider is a realization o

  • Android Learning Content Provider of Data Storage 2010-12-05

    Android is how to implement data sharing between applications? An application can be fully exposed to their own data, the outside world can not see more of this, do not expose the application to see how data is stored, or use a file or database, or t

  • the use of android Content Provider 2010-12-07

    Content Provider Android application is one of the components, as an application to share data between the only way, Content Provider main function is to store and retrieve data and to provide access to data in other applications excuse. Android syst

  • content provider in-depth analysis 2010-12-15

    Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only require

  • Preparation of content provider 2011-01-02

    Android in the content provider provides a mechanism for sharing data between processes. Conetent provider database table in a similar mechanism to interact with the outside method. content provider's implementation does not make requirements on the

  • Analysis of the content provider android 2011-05-27

    The system has two applications, more complicated. But the content provider is the android in the very, very important, and we have to learn the next, oh. Look at the renderings, we offer four buttons, click the button corresponding operation will be

  • 浅谈Android Content Provider的使用 2014-02-09

    本篇文章小编为大家介绍,Android Content Provider的使用.需要的朋友参考下 Content Provider:一个组件,必须放在应用的主包或应用的子包之下: 组件的配置需要在清单文件中进行配置:content provider需要在application节点中进行配置: 内容提供者在应用中的作用是对外共享数据(任意类型的数据)使用的,别的程序可以对数据进行CRUD,如通讯录: 如果采用文件的方式对外共享数据,会因为文件的类型不同而需要使用不同的api访问方式导致访问繁杂,而

  • Android基础 : Android Content Provider[转] 2010-01-06

    Android应用程序可以使用文件或SqlLite数据库来存储数据.Content Provider提供了一种多应用间数据共享的方式,比如:联系人信息可以被多个应用程序访问.Content Provider是个实现了一组用于提供其他应用程序存取数据的标准方法的类. 应用程序可以在Content Provider中执行如下操作: 查询数据 修改数据 添加数据 删除数据 标准的Content Provider: Android提供了一些已经在系统中实现的标准Content Provider,比如联系