Home Java javaTutorial Android content provider ContentProvider usage example analysis

Android content provider ContentProvider usage example analysis

Feb 07, 2017 pm 04:01 PM

The examples in this article describe the usage of Android content provider ContentProvider. Share it with everyone for your reference, as follows:

PersonContentProvider content provider class

package com.ljq.db;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
/**
 * 内容提供者
 * 
 * 作用:统一数据访问方式,方便外部调用
 * 
 * @author jiqinlin
 * 
 */
public class PersonContentProvider extends ContentProvider {
  // 数据集的MIME类型字符串则应该以vnd.android.cursor.dir/开头
  public static final String PERSONS_TYPE = "vnd.android.cursor.dir/person";
  // 单一数据的MIME类型字符串应该以vnd.android.cursor.item/开头
  public static final String PERSONS_ITEM_TYPE = "vnd.android.cursor.item/person";
  public static final String AUTHORITY = "com.ljq.provider.personprovider";// 主机名
  /* 自定义匹配码 */
  public static final int PERSONS = 1;
  /* 自定义匹配码 */
  public static final int PERSON = 2;
  public static final Uri PERSONS_URI = Uri.parse("content://" + AUTHORITY + "/person");
  private DBOpenHelper dbOpenHelper = null;
  // UriMatcher类用来匹配Uri,使用match()方法匹配路径时返回匹配码
  private static final UriMatcher uriMatcher;
  static {
    // 常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    // 如果match()方法匹配content://com.ljq.provider.personprovider/person路径,返回匹配码为PERSONS
    uriMatcher.addURI(AUTHORITY, "person", PERSONS);
    // 如果match()方法匹配content://com.ljq.provider.personprovider/person/230路径,返回匹配码为PERSON
    uriMatcher.addURI(AUTHORITY, "person/#", PERSON);
  }
  @Override
  public boolean onCreate() {
    dbOpenHelper = new DBOpenHelper(this.getContext());
    return true;
  }
  @Override
  public Uri insert(Uri uri, ContentValues values){
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    long id = 0;
    switch (uriMatcher.match(uri)) {
    case PERSONS:
      id = db.insert("person", "name", values);// 返回的是记录的行号,主键为int,实际上就是主键值
      return ContentUris.withAppendedId(uri, id);
    case PERSON:
      id = db.insert("person", "name", values);
      String path = uri.toString();
      return Uri.parse(path.substring(0, path.lastIndexOf("/"))+id); // 替换掉id
    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }
  }
  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    int count = 0;
    switch (uriMatcher.match(uri)) {
    case PERSONS:
      count = db.delete("person", selection, selectionArgs);
      break;
    case PERSON:
      // 下面的方法用于从URI中解析出id,对这样的路径content://com.ljq.provider.personprovider/person/10
      // 进行解析,返回值为10
      long personid = ContentUris.parseId(uri);
      String where = "id=" + personid;// 删除指定id的记录
      where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它条件附加上
      count = db.delete("person", where, selectionArgs);
      break;
    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }
    db.close();
    return count;
  }
  @Override
  public int update(Uri uri, ContentValues values, String selection,
      String[] selectionArgs) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    int count = 0;
    switch (uriMatcher.match(uri)) {
    case PERSONS:
      count = db.update("person", values, selection, selectionArgs);
      break;
    case PERSON:
      // 下面的方法用于从URI中解析出id,对这样的路径content://com.ljq.provider.personprovider/person/10
      // 进行解析,返回值为10
      long personid = ContentUris.parseId(uri);
      String where = "id=" + personid;// 获取指定id的记录
      where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它条件附加上
      count = db.update("person", values, where, selectionArgs);
      break;
    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }
    db.close();
    return count;
  }
  @Override
  public String getType(Uri uri) {
    switch (uriMatcher.match(uri)) {
    case PERSONS:
      return PERSONS_TYPE;
    case PERSON:
      return PERSONS_ITEM_TYPE;
    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }
  }
  @Override
  public Cursor query(Uri uri, String[] projection, String selection,
      String[] selectionArgs, String sortOrder) {
    SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
    switch (uriMatcher.match(uri)) {
    case PERSONS:
      return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
    case PERSON:
      // 下面的方法用于从URI中解析出id,对这样的路径content://com.ljq.provider.personprovider/person/10
      // 进行解析,返回值为10
      long personid = ContentUris.parseId(uri);
      String where = "id=" + personid;// 获取指定id的记录
      where += !TextUtils.isEmpty(selection) ? " and (" + selection + ")" : "";// 把其它条件附加上
      return db.query("person", projection, where, selectionArgs, null, null, sortOrder);
    default:
      throw new IllegalArgumentException("Unknown URI " + uri);
    }
  }
}
Copy after login

File list

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.ljq.sql" android:versionCode="1"
  android:versionName="1.0">
  <application android:icon="@drawable/icon"
    android:label="@string/app_name">
    <uses-library android:name="android.test.runner" />
    <activity android:name=".SqlActivity"
      android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category
          android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <provider android:name="com.ljq.db.PersonContentProvider"
       android:authorities="com.ljq.provider.personprovider" />
  </application>
  <uses-sdk android:minSdkVersion="7" />
  <instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="com.ljq.sql" android:label="Tests for My App" />
</manifest>
Copy after login

PersonContentProviderTest content provider test class

package com.ljq.test;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.Log;
/**
 * 外部访问内容提供者
 * 
 * @author jiqinlin
 *
 */
public class PersonContentProviderTest extends AndroidTestCase{
  private static final String TAG = "PersonContentProviderTest";
  public void testSave() throws Throwable{
    ContentResolver contentResolver = this.getContext().getContentResolver();
    Uri insertUri = Uri.parse("content://com.ljq.provider.personprovider/person");
    ContentValues values = new ContentValues();
    values.put("name", "ljq");
    values.put("phone", "1350000009");
    Uri uri = contentResolver.insert(insertUri, values);
    Log.i(TAG, uri.toString());
  }
  public void testUpdate() throws Throwable{
    ContentResolver contentResolver = this.getContext().getContentResolver();
    Uri updateUri = Uri.parse("content://com.ljq.provider.personprovider/person/1");
    ContentValues values = new ContentValues();
    values.put("name", "linjiqin");
    contentResolver.update(updateUri, values, null, null);
  }
  public void testFind() throws Throwable{
    ContentResolver contentResolver = this.getContext().getContentResolver();
    //Uri uri = Uri.parse("content://com.ljq.provider.personprovider/person");
    Uri uri = Uri.parse("content://com.ljq.provider.personprovider/person");
    Cursor cursor = contentResolver.query(uri, null, null, null, "id asc");
    while(cursor.moveToNext()){
      int personid = cursor.getInt(cursor.getColumnIndex("id"));
      String name = cursor.getString(cursor.getColumnIndex("name"));
      String phone = cursor.getString(cursor.getColumnIndex("phone"));
      Log.i(TAG, "personid="+ personid + ",name="+ name+ ",phone="+ phone);
    }
    cursor.close();
  }
  public void testDelete() throws Throwable{
    ContentResolver contentResolver = this.getContext().getContentResolver();
    Uri uri = Uri.parse("content://com.ljq.provider.personprovider/person/1");
    contentResolver.delete(uri, null, null);
  }
}
Copy after login

I hope this article will be helpful to everyone in Android programming.

For more Android content provider ContentProvider usage example analysis and related articles, please pay attention to the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles