欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android内容提供者ContentProvider用法实例分析

程序员文章站 2024-02-27 21:50:33
本文实例讲述了android内容提供者contentprovider用法。分享给大家供大家参考,具体如下: personcontentprovider内容提供者类...

本文实例讲述了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调试技巧与常见问题解决方法汇总》、《android开发入门与进阶教程》、《android多媒体操作技巧汇总(音频,视频,录音等)》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。