Home > Java > javaTutorial > Implementation of Android ContentProvider and simple example code

Implementation of Android ContentProvider and simple example code

高洛峰
Release: 2017-02-07 15:47:59
Original
1530 people have browsed it

1. Concept and description

ContentProvider definition:

Content provider is the basic module of an Android application, which provides content to the application. They encapsulate data and Provide it to the application through this ContentResolver interface, and use ContentProvider to share data between different applications. Android provides ContentProvider (video, audio) for some common data. ContentProvider uses the form of a table to organize data.

URI definition:

Each ContentProvider has a public URI, which is used to represent the data provided by this ContentProvider. ContentProviders provided by android are stored in android.provider.

2. The process of implementing ContentProvider

1. Define the constants needed for ContentProvider (the most important thing is to define CONTENT_URI, CONTENT_URI is a Uri type, the fact is obtained through string parsing)

//定义ContentProvider所需要的常量 
public class FirstProviderMetaData { 
  
  // AUTHORIY等于自己的创建ContentProvider类的完全路径 
  public static final String AUTHORIY = "com.example.firstconent.FirstContentProvider"; 
  
  // 数据库的名称 
  public static final String DATABASE_NAME = "FirstProvider.db"; 
  
  // BaseColumns有两个字段_id和_count 
  public static final class UserTableMetaData implements BaseColumns { 
    // 表名 
    public static final String TABLE_NAME = "t_user"; 
    // 访问该ContentProvider的URI 
    public static final Uri CONTENT_URI = Uri 
        .parse("content://" + AUTHORIY); 
  
    // 表的数据类型 
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/users"; 
    // 一列的数据类型 
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/users"; 
  
    // 一个字段 
    public static final String USER_NAME = "name"; 
  
    // 默认排序 
    public static final String DEFAULT_SORT_ORDER = "_id desc"; 
  } 
}
Copy after login

2. Define a class that inherits ContentProvider

3. Implement query, insert, update, delete, getType and onCreate methods

(1). Define UriMatcher

// 匹配Uri,检查Uri的合法性
  public static final UriMatcher uriMatcher;
  public static final int INCOMING_USER_COLLECTION = 1;
  public static final int INCOMING_USER_SIGNLE = 2;
  static {
    // 创建一个uri树的根结点
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    // 添加uri匹配对,如果这个匹配成功,则code值则会返回。
    uriMatcher.addURI(FirstProviderMetaData.AUTHORIY, "/t_user",
        INCOMING_USER_COLLECTION);
    uriMatcher.addURI(FirstProviderMetaData.AUTHORIY, "/t_user/#",
        INCOMING_USER_SIGNLE);
  
  }
Copy after login

(2). Rewrite getType method

// 根据传入uri,所回该uri所表示的数据类型
  @Override
  public String getType(Uri uri) {
    // TODO Auto-generated method stub
    switch (uriMatcher.match(uri)) {
    case INCOMING_USER_COLLECTION:
      return UserTableMetaData.CONTENT_TYPE;
    case INCOMING_USER_SIGNLE:
      return UserTableMetaData.CONTENT_ITEM_TYPE;
    default:
      throw new IllegalArgumentException("Unknown URI" + uri);
    }
  
  }
Copy after login

(3). Create userProjectMap hash Map static object

public static HashMap<String, String> userProjectMap;
  static {
    userProjectMap = new HashMap<String, String>();
    userProjectMap.put(UserTableMetaData._ID, UserTableMetaData._ID);
    userProjectMap.put(UserTableMetaData.USER_NAME,
        UserTableMetaData.USER_NAME);
  }
Copy after login

(4). Rewrite insert method

// 该方法返回值是一个uri,这个uri表示的刚刚使用这个方法所插入的数据
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // TODO Auto-generated method stub
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    // rowId是新插入数据的id
    long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);
    // 正常插入,-1为出常错误
    if (rowId != -1) {
      // 添加一个id到这个路径的结尾
      Uri insertUserUri = ContentUris.withAppendedId(
          UserTableMetaData.CONTENT_URI, rowId);
      // 得到一个ContentResolver实例.
      ContentResolver cr = this.getContext().getContentResolver();
      // 通辞呈数据改变
      cr.notifyChange(insertUserUri, null);
  
      return insertUserUri;
    } else {
      throw new SQLException("Failed to insert row into" + uri);
    }
  }
Copy after login

(5). Rewrite query method

@Override
  public Cursor query(Uri uri, String[] projection, String selection,
      String[] selectionArgs, String sortOrder) {
    // TODO Auto-generated method stub
    SQLiteQueryBuilder sqb = new SQLiteQueryBuilder();
    switch (uriMatcher.match(uri)) {
    case INCOMING_USER_COLLECTION:
      sqb.setTables(UserTableMetaData.TABLE_NAME);
      sqb.setProjectionMap(userProjectMap);
      break;
    case INCOMING_USER_SIGNLE:
      sqb.setTables(UserTableMetaData.TABLE_NAME);
      sqb.setProjectionMap(userProjectMap);
  
      String idKey = UserTableMetaData._ID;
      // 1得到path集合
      // 2取它的集合的第2个元素
      // 例如:CONTENT_URI等于content://com.example.firstconent.FirstContentProvider/t_user/id,
      // content://为协议
      // com.example.firstconent.FirstContentProvider为authoriy
      // /t_user/id为path
      String idValue = uri.getPathSegments().get(1);
  
      sqb.appendWhere(idKey + "=" + idValue);
      break;
    }
    String orderBy = null;
    if (TextUtils.isEmpty(sortOrder)) {
      orderBy = UserTableMetaData.DEFAULT_SORT_ORDER;
    } else {
      orderBy = sortOrder;
    }
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    Cursor cursor = sqb.query(db, projection, selection, selectionArgs,
        null, null, orderBy);
    ContentResolver cr = this.getContext().getContentResolver();
    // 通适数据变动
    cursor.setNotificationUri(cr, uri);
    return cursor;
  }
Copy after login

4. Declare

<provider
      android:name="com.example.firstcontent.FirstContentProvider"
      android:authorities="com.example.first.firstcontent.FirstContentProvider" >
    </provider>
Copy after login

in AndroidManifest.xml. Thank you for reading. I hope it can help everyone. Thank you for your support of this site!

For more articles related to the implementation of Android ContentProvider and simple example codes, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template