首頁 Java java教程 Android內容提供者ContentProvider用法實例分析

Android內容提供者ContentProvider用法實例分析

Feb 07, 2017 pm 04:01 PM

本文實例講述了Android內容提供者ContentProvider用法。分享給大家參考,具體如下:

PersonContentProvider內容提供者類別

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);
    }
  }
}
登入後複製

檔案清單

<?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>
登入後複製

PersonContentProviderTest內容提供者測試類別

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);
  }
}
登入後複製

希望本文所述對Android程式設計程式有所幫助。

更多Android內容提供者ContentProvider用法實例分析相關文章請關注PHP中文網!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1655
14
CakePHP 教程
1413
52
Laravel 教程
1306
25
PHP教程
1252
29
C# 教程
1226
24
公司安全軟件導致應用無法運行?如何排查和解決? 公司安全軟件導致應用無法運行?如何排查和解決? Apr 19, 2025 pm 04:51 PM

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

如何將姓名轉換為數字以實現排序並保持群組中的一致性? 如何將姓名轉換為數字以實現排序並保持群組中的一致性? Apr 19, 2025 pm 11:30 PM

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

如何使用MapStruct簡化系統對接中的字段映射問題? 如何使用MapStruct簡化系統對接中的字段映射問題? Apr 19, 2025 pm 06:21 PM

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

如何優雅地獲取實體類變量名構建數據庫查詢條件? 如何優雅地獲取實體類變量名構建數據庫查詢條件? Apr 19, 2025 pm 11:42 PM

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? IntelliJ IDEA是如何在不輸出日誌的情況下識別Spring Boot項目的端口號的? Apr 19, 2025 pm 11:45 PM

在使用IntelliJIDEAUltimate版本啟動Spring...

Java對像如何安全地轉換為數組? Java對像如何安全地轉換為數組? Apr 19, 2025 pm 11:33 PM

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? 電商平台SKU和SPU數據庫設計:如何兼顧用戶自定義屬性和無屬性商品? Apr 19, 2025 pm 11:27 PM

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...

如何利用Redis緩存方案高效實現產品排行榜列表的需求? 如何利用Redis緩存方案高效實現產品排行榜列表的需求? Apr 19, 2025 pm 11:36 PM

Redis緩存方案如何實現產品排行榜列表的需求?在開發過程中,我們常常需要處理排行榜的需求,例如展示一個�...

See all articles