Chinaunix首页 | 论坛 | 博客
  • 博客访问: 900102
  • 博文数量: 322
  • 博客积分: 6688
  • 博客等级: 准将
  • 技术积分: 3626
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-19 11:26
文章分类

全部博文(322)

文章存档

2013年(5)

2012年(66)

2011年(87)

2010年(164)

分类: Java

2011-01-07 09:18:44

Content provider

Android工程db

PersonContentProvider

Java代码

  1. package org.wp.db;
  2.  
  3. /**
  4.  *
  5.  * 当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法
  6.  * 就可以向其他应用共享其数据
  7.  * 虽然使用其他方法也可以对外共享数据,但数据访问方式会因数据存储的方式而不同
  8.  * 如:采用文件方式对外共享数据,需要进行文件操作读写数据
  9.  * 采用sharedpreferences共享数据,需要使用sharedpreferences API读写数据
  10.  * 而使用ContentProvider共享数据的好处是统一了数据访问方式
  11.  * 当应用需要通过ContentProvider对外共享数据时
  12.  *
  13.  * 第一步需要继承ContentProvider并重写下面方法
  14.  * public class PersonContentProvider extends ContentProvider{
  15.  * public boolean onCreate()
  16.  * public Uri insert(Uri uri, ContentValues values)
  17.  * public int delete(Uri uri, String selection, String[] selectionArgs)
  18.  * public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
  19.  * public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
  20.  * public String getType(Uri uri)
  21.  * }
  22.  *
  23.  * 第二步需要在AndroidManifest.xml使用对该ContentProvider进行配置
  24.  * 为了能让其他应用找到该ContentProvider
  25.  * ContentProvider 采用了authorities(主机名/域名)对它进行唯一标识,
  26.  *
  27.  *
  28.  *
  29.  * android:authorities="org.wp.provider.personprovider" />
  30.  *
  31.  *
  32.  *
  33.  * Uri代表了要操作的数据,Uri主要包含了两部分信息
  34.  * 1.需要操作的ContentProvider
  35.  * 2.对ContentProvider中的什么数据进行操作
  36.  *
  37.  * ContentProvider(内容提供者)的scheme已经由Android所规定
  38.  * scheme为:content://
  39.  * 主机名(或叫Authority)用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它
  40.  * 路径(path)可以用来表示我们要操作的数据,路径的构建应根据业务而定,如下
  41.  * 要操作person表中id为10的记录,可以构建这样的路径:/person/10
  42.  * 要操作person表中id为10的记录的name字段, person/10/name
  43.  * 要操作person表中的所有记录,可以构建这样的路径:/person
  44.  * 要操作xxx表中的记录,可以构建这样的路径:/xxx
  45.  * 当然要操作的数据不一定来自数据库,也可以是文件等他存储方式,如下
  46.  * 要操作xml文件中person节点下的name节点,可以构建这样的路径:/person/name
  47.  *
  48.  *
  49.  * 如果要把一个字符串转换成Uri,可以使用Uri类中的parse()方法,如下
  50.  * Uri uri = Uri.parse("content://org.wp.provider.personprovider/person")
  51.  *
  52.  *
  53.  * ContentProvider类主要方法的作用
  54.  * public boolean onCreate()
  55.  * 该方法在ContentProvider创建后就会被调用, Android在系统启动时就会创建ContentProvider
  56.  * public Uri insert(Uri uri, ContentValues values)
  57.  * 该方法用于供外部应用往ContentProvider添加数据
  58.  * public int delete(Uri uri, String selection, String[] selectionArgs)
  59.  * 该方法用于供外部应用从ContentProvider删除数据
  60.  * public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
  61.  * 该方法用于供外部应用更新ContentProvider中的数据
  62.  * public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
  63.  * 该方法用于供外部应用从ContentProvider中获取数据
  64.  * public String getType(Uri uri)
  65.  * 该方法用于返回当前Url所代表数据的MIME类型
  66.  * 如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头
  67.  * 例如:要得到所有person记录的Uri为content://org.wp.provider.personprovider/person
  68.  * 那么返回的MIME类型字符串应该为:"vnd.android.cursor.dir/person"
  69.  * 如果要操作的数据属于单一数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头
  70.  * 例如:得到id为10的person记录,Uri为content://org.wp.provider.personprovider/person/10
  71.  * 那么返回的MIME类型字符串应该为:"vnd.android.cursor.item/person"
  72.  *
  73.  */
  74.  
  75. import org.wp.service.DataBaseOpenHelper;
  76. import android.content.ContentProvider;
  77. import android.content.ContentUris;
  78. import android.content.ContentValues;
  79. import android.content.UriMatcher;
  80. import android.database.Cursor;
  81. import android.database.sqlite.SQLiteDatabase;
  82. import android.net.Uri;
  83. import android.text.TextUtils;
  84.  
  85. public class PersonContentProvider extends ContentProvider {
  86.     private DataBaseOpenHelper dataBaseOpenHelper;
  87.     private static final int ALLPERSON = 1;
  88.     private static final int PERSON = 2;
  89.  
  90.     /**
  91.      * UriMatcher类使用介绍
  92.      * 因为Uri代表了要操作的数据,所以我们很经常需要解析Uri,并从Uri中获取数据
  93.      * Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris
  94.      * UriMatcher类用于匹配Uri,它的用法如下
  95.      * 首先第一步把你需要匹配Uri路径全部给注册上,如下
  96.      * 常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
  97.      *
  98.      * UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  99.      * 如果match()方法匹配content://org.wp.provider.personprovider/person路径,返回匹配码为1
  100.      * uriMatcher.addURI("org.wp.provider.personprovider", "person", ALLPERSON);
  101.      * 添加需要匹配uri,如果匹配就会返回匹配码
  102.      *
  103.      * 如果match()方法匹配content://org.wp.provider.personprovider/person/230路径,返回匹配码为2
  104.      * uriMatcher.addURI("org.wp.provider.personprovider", "person/#", PERSON);//#号为通配符
  105.      * 注册完需要匹配的Uri后,就可以使用uriMatcher.match(uri)方法对输入的Uri进行匹配
  106.      * 如果匹配就返回匹配码,匹配码是调用addURI()方法传入的第三个参数
  107.      * 假设匹配content://org.wp.provider.personprovider/person路径 返回的匹配码为1
  108.      *
  109.      *
  110.      * ContentUris类使用介绍
  111.      * ContentUris类用于获取Uri路径后面的ID部分,它有两个比较实用的方法
  112.      * withAppendedId(uri, id)用于为路径加上ID部分
  113.      * Uri uri = Uri.parse("content://org.wp.provider.personprovider/person")
  114.      * Uri resultUri = ContentUris.withAppendedId(uri, 10);
  115.      * 生成后的Uri为:content://org.wp.provider.personprovider/person/10
  116.      *
  117.      * parseId(uri)方法用于从路径中获取ID部分:
  118.      * Uri uri = Uri.parse("content://org.wp.provider.personprovider/person/10")
  119.      * long personid = ContentUris.parseId(uri);
  120.      * 获取的结果为:10
  121.      *
  122.      */
  123.  
  124.     private static final UriMatcher uriMatcher = new UriMatcher(
  125.             UriMatcher.NO_MATCH);
  126.  
  127.     /**
  128.      * 静态代码块(static block )
  129.      * 不包含在任何方法体中
  130.      * 当类被载入时
  131.      * 自动执行静态代码块且只被执行一次
  132.      * 经常用于类属性的初始化
  133.      */
  134.     static {
  135.         uriMatcher.addURI("org.wp.provider.personprovider", "person", ALLPERSON);
  136.         uriMatcher.addURI("org.wp.provider.personprovider", "person/#", PERSON);
  137.     }
  138.  
  139.     @Override
  140.     public boolean onCreate() {
  141.         dataBaseOpenHelper = new DataBaseOpenHelper(this.getContext());
  142.         return true;
  143.     }
  144.  
  145.     @Override
  146.     public String getType(Uri uri) {
  147.         switch (uriMatcher.match(uri)) {
  148.         case ALLPERSON:
  149.             return "vnd.android.cursor.dir/personprovider.person";
  150.         case PERSON:
  151.             return "vnd.android.cursor.item/personprovider.person";
  152.         default:
  153.             throw new IllegalArgumentException("Unknow Uri:" + uri);
  154.         }
  155.     }
  156.  
  157.     @Override
  158.     public int delete(Uri uri, String selection, String[] selectionArgs) {
  159.         SQLiteDatabase db = dataBaseOpenHelper.getWritableDatabase();
  160.         int count = 0;
  161.         switch (uriMatcher.match(uri)) {
  162.         case ALLPERSON:
  163.             count = db.delete("person", selection, selectionArgs);
  164.             break;
  165.         case PERSON:
  166.             long personid = ContentUris.parseId(uri);
  167.             String condition = TextUtils.isEmpty(selection) ? "personid=?"
  168.                     : selection + " and personid=?";
  169.             String params[] = new String[] { String.valueOf(personid) };
  170.             if (!TextUtils.isEmpty(selection) && selectionArgs != null) {
  171.                 params = new String[selectionArgs.length + 1];
  172.                 for (int i = 0; i < selectionArgs.length; i++) {
  173.                     params[i] = selectionArgs[i];
  174.                 }
  175.                 params[selectionArgs.length] = String.valueOf(personid);
  176.             }
  177.             count = db.delete("person", condition, params);
  178.             break;
  179.         default:
  180.             throw new IllegalArgumentException("Unknow Uri:" + uri);
  181.         }
  182.         return count;
  183.     }
  184.  
  185.     @Override
  186.     public Uri insert(Uri uri, ContentValues values) {
  187.         SQLiteDatabase db = dataBaseOpenHelper.getWritableDatabase();
  188.         long id = 0;
  189.         switch (uriMatcher.match(uri)) {
  190.         case ALLPERSON:
  191.             // 返回的是记录的行号,主键为int,实际上就是主键值
  192.             id = db.insert("person", "name", values);
  193.             return ContentUris.withAppendedId(uri, id);
  194.         case PERSON:
  195.             id = db.insert("person", "name", values);
  196.             String path = uri.toString();
  197.             return Uri.parse(path.substring(0, path.lastIndexOf("/")) + id);
  198.         default:
  199.             // 非法参数异常
  200.             throw new IllegalArgumentException("Unknow Uri" + uri);
  201.         }
  202.     }
  203.  
  204.     @Override
  205.     public Cursor query(Uri uri, String[] projection, String selection,
  206.             String[] selectionArgs, String sortOrder) {
  207.         SQLiteDatabase db = dataBaseOpenHelper.getReadableDatabase();
  208.         switch (uriMatcher.match(uri)) {
  209.         case ALLPERSON:
  210.             return db.query("person", projection, selection, selectionArgs,
  211.                     null, null, sortOrder);
  212.         case PERSON:
  213.             long personid = ContentUris.parseId(uri);
  214.             String condition = TextUtils.isEmpty(selection) ? "personid=?"
  215.                     : selection + " and personid=?";
  216.             String params[] = new String[] { String.valueOf(personid) };
  217.             if (!TextUtils.isEmpty(selection) && selectionArgs != null) {
  218.                 params = new String[selectionArgs.length + 1];
  219.                 for (int i = 0; i < selectionArgs.length; i++) {
  220.                     params[i] = selectionArgs[i];
  221.                 }
  222.                 params[selectionArgs.length] = String.valueOf(personid);
  223.             }
  224.             return db.query("person", projection, condition, params, null,
  225.                     null, sortOrder);
  226.         default:
  227.             throw new IllegalArgumentException("Unknow Uri:" + uri);
  228.         }
  229.     }
  230.  
  231.     @Override
  232.     public int update(Uri uri, ContentValues values, String selection,
  233.             String[] selectionArgs) {
  234.         SQLiteDatabase db = dataBaseOpenHelper.getWritableDatabase();
  235.         int count = 0;
  236.         switch (uriMatcher.match(uri)) {
  237.         case ALLPERSON:
  238.             count = db.update("person", values, selection, selectionArgs);
  239.             break;
  240.         case PERSON:
  241.             long personid = ContentUris.parseId(uri);
  242.             String condition = TextUtils.isEmpty(selection) ? "personid=?"
  243.                     : selection + " and personid=?";
  244.             String params[] = new String[] { String.valueOf(personid) };
  245.             if (!TextUtils.isEmpty(selection) && selectionArgs != null) {
  246.                 params = new String[selectionArgs.length + 1];
  247.                 for (int i = 0; i < selectionArgs.length; i++) {
  248.                     params[i] = selectionArgs[i];
  249.                 }
  250.                 params[selectionArgs.length] = String.valueOf(personid);
  251.             }
  252.             count = db.update("person", values, condition, params);
  253.             break;
  254.         default:
  255.             throw new IllegalArgumentException("Unknow Uri:" + uri);
  256.         }
  257.         return count;
  258.     }
  259. }

AndroidManifest.xml

Xml代码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android=""
  3.     package="org.wp.db" android:versionCode="1" android:versionName="1.0">
  4.     <application android:icon="@drawable/icon" android:label="@string/app_name">
  5.         <!-- 配置 ContentProvider -->
  6.         <provider android:name=".PersonContentProvider"
  7.             android:authorities="org.wp.provider.personprovider" />
  8.         <uses-library android:name="android.test.runner" />
  9.         <activity android:name=".DBActivity" android:label="@string/app_name">
  10.             <intent-filter>
  11.                 <action android:name="android.intent.action.MAIN" />
  12.                 <category android:name="android.intent.category.LAUNCHER" />
  13.             </intent-filter 
  14.         </activity>
  15.     </application>
  16.     <uses-sdk android:minSdkVersion="7" />
  17.     <instrumentation android:name="android.test.InstrumentationTestRunner"
  18.         android:targetPackage="org.wp.db" android:label="Tests for My App" />
  19. </manifest>

Android工程contentProviderUser

ContentProviderUserActivity

Java代码

  1. package org.wp.user;
  2.  
  3. /**
  4.  *
  5.  * 使用ContentResolver操作ContentProvider中的数据
  6.  * 当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时
  7.  * 可以使用ContentResolver 类来完成,要获取ContentResolver 对象
  8.  * 可以使用Activity提供的getContentResolver()方法
  9.  * ContentResolver 类提供了与ContentProvider类相同签名的四个方法:
  10.  * public Uri insert(Uri uri, ContentValues values)
  11.  * 该方法用于往ContentProvider添加数据
  12.  * public int delete(Uri uri, String selection, String[] selectionArgs)
  13.  * 该方法用于从ContentProvider删除数据
  14.  * public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
  15.  * 该方法用于更新ContentProvider中的数据
  16.  * public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
  17.  * 该方法用于从ContentProvider中获取数据
  18.  *
  19.  * 这些方法的第一个参数为Uri,代表要操作的是哪个ContentProvider和对其中的什么数据进行操作
  20.  * 假设给定的是: Uri.parse("content://org.wp.provider.personprovider/person/10")
  21.  * 那么将会对主机名为org.wp.provider.personprovider的ContentProvider进行操作
  22.  * 操作的数据为person表中id为10的记录
  23.  *
  24.  */
  25.  
  26. import android.app.Activity;
  27. import android.content.ContentResolver;
  28. import android.content.ContentValues;
  29. import android.database.Cursor;
  30. import android.net.Uri;
  31. import android.os.Bundle;
  32. import android.provider.ContactsContract;
  33. import android.util.Log;
  34.  
  35. public class ContentProviderUserActivity extends Activity {
  36.     private static final String TAG = "ContentProviderUserActivity";
  37.  
  38.     @Override
  39.     public void onCreate(Bundle savedInstanceState) {
  40.         super.onCreate(savedInstanceState);
  41.         setContentView(R.layout.main);
  42.  
  43.         ContentResolver contentResolver = this.getContentResolver();
  44.         Uri uri = Uri.parse("content://org.wp.provider.personprovider/person/");
  45.         ContentValues values = new ContentValues();
  46.  
  47.         // 添加一条记录
  48.         values.put("name", "张二");
  49.         values.put("age", (short) 28);
  50.         contentResolver.insert(uri, values);
  51.  
  52.         // 修改记录
  53.         uri = Uri.parse("content://org.wp.provider.personprovider/person/2");
  54.         values.put("name", "laoli");
  55.         values.put("age", (short) 66);
  56.         contentResolver.update(uri, values, "age = ?", new String[] { "35" });
  57.  
  58.         // 删除记录
  59.         uri = Uri.parse("content://org.wp.provider.personprovider/person/3");
  60.         contentResolver.delete(uri, null, null);
  61.  
  62.         // 获取person表中所有记录
  63.         uri = Uri.parse("content://org.wp.provider.personprovider/person/");
  64.         Cursor cursor = contentResolver.query(uri, new String[] { "personid",
  65.                 "name", "age" }, null, null, "personid desc");
  66.         while (cursor.moveToNext()) {
  67.             Log.i(TAG, "personid:" + cursor.getInt(0) + ",name:"
  68.                     + cursor.getString(1) + ",age" + cursor.getShort(2));
  69.         }
  70.         cursor.close();
  71.  
  72.         // 获取联系人信息
  73.         Cursor cur = contentResolver.query(
  74.                 ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
  75.         while (cur.moveToNext()) {
  76.             int contactId = cur.getInt(cur
  77.                     .getColumnIndex(ContactsContract.Contacts._ID));
  78.             String name = cur.getString(cur
  79.                     .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
  80.             Log.i(TAG, "contactId=" + contactId + ",name" + name);
  81.             Cursor phones = getContentResolver().query(
  82.                     ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
  83.                     null,
  84.                     ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
  85.                             + contactId, null, null);
  86.             StringBuilder sb = new StringBuilder();
  87.             while (phones.moveToNext()) {
  88.                 String phoneNumber = phones
  89.                         .getString(phones
  90.                                 .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
  91.                 sb.append(phoneNumber).append(",");
  92.             }
  93.             sb.deleteCharAt(sb.length() - 1);
  94.             Log.i(TAG, sb.toString());
  95.         }
  96.         cur.close();
  97.     }
  98. }

AndroidManifest.xml

Xml代码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android=""
  3.     package="org.wp.user" android:versionCode="1" android:versionName="1.0">
  4.     <application android:icon="@drawable/icon" android:label="@string/app_name">
  5.         <activity android:name=".ContentProviderUserActivity"
  6.             android:label="@string/app_name">
  7.             <intent-filter>
  8.                 <action android:name="android.intent.action.MAIN" />
  9.                 <category android:name="android.intent.category.LAUNCHER" />
  10.             </intent-filter>
  11.         </activity>
  12.     </application>
  13.     <uses-sdk android:minSdkVersion="7" />
  14.     <uses-permission android:name="android.permission.READ_CONTACTS" />
  15. </manifest>

阅读(2254) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~