Android内容提供者源码

Android内容提供者源码,我不想说多,只讲一些实用的代码,增删改查。通过contentProvider向数据进行操作。大家可以下载,通过日志与LogCat打印出来的信息作为参考!

package com.smart;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;

public class ContentProvider extends Activity {
  private static final String TAG = "ContentProvider";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
//      通过这个类,方问DB项目
      ContentResolver contentResolver = this.getContentResolver();
      Uri alluri = Uri.parse("content://com.smart.provider.personprovider/person");
//      Uri uri = Uri.parse("content://com.smart.provider.personprovider/person");
      ContentValues values = new ContentValues();
      values.put("name", "smart99"); // 这里更改就可以了。/
      values.put("age", (short)44);
//      contentResolver.insert(uri, values); //增加
      
      Uri uri = Uri.parse("content://com.smart.provider.personprovider/person/5");
//      contentResolver.update(uri, values, null, null);//更新
//      contentResolver.delete(uri, null, null);//删除
      
      
      
      //查询
//      Cursor cursor = contentResolver.query(uri, new String[] {
//        "personid", "name", "age" }, null, null, "personid desc");
//      while (cursor.moveToNext()) {
//       Log.i(TAG,
//         "personid=" + cursor.getInt(0) + ",name="
//           + cursor.getString(1) + ",age="
//           + cursor.getShort(2));
//      }
//      cursor.close();
//      记得要关掉数据
      
      //01:19
      
      contactMethod();
    }
    //读取通迅里的人员。
 public void contactMethod(){
 //联系人,/媒体库/
 ContentResolver contentResolver = this.getContentResolver();
 Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
 
 while (cursor.moveToNext()) {
  
  int contactId=cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
  String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
  Log.i(TAG,"contactId=" + contactId + ",name="
      + name);
  
  
  Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+contactId, null, null);
  StringBuffer sb=new StringBuffer();
  while(phones.moveToNext()){
   String phoneNumber=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
  sb.append(phoneNumber).append(",");
  
 }
  //电话号码可以得到
  Log.i(TAG, sb.toString());
 
 }
 
 cursor.close();
 
}
    
    
}





package com.smart.dh;

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;

import com.smart.service.DataBaseOpenHelper;

/**
 * 使用内容提供者
ContentProvider共享数据
当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法
就可以向其它应用共享其数据。虽然使用其它方法对外共享数据,但是数据访问
方式 会因数据存储的方式而不同。,而采用文件操作读写数据,采用sharedoreferences共享数据的需要使用sharedpreferences API读写数据,而使用ContentProvider共享数据的好处
好处是统一了数据访问方式,当应用需要通过ContentProvider对外共享 数据时,第一步需要继承ContentProvider并重写下面的方法。
Public class PersonContentProvider extends ContentProvider{
Public boolean onCreate();
Public Uri insert(Uri uri,ContentValues values);
Public int delete(Uri uri,String selection,String[] selectionArgs);
Public int update(Uri uri,ContentValues values,String selection,String selectionArgs);
Pullic Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String softOrder);
Public String getType(Uri uri);
}

第二步需要在AndroidMandifest.xml使用<provider>对该ContentProvider进行配置,为了能让其它应用找到该ContentProvider,ContentProvider采用了authorites(主机名、域名)对它进行唯一标识,你可以把ContentProvider看作是一个网站(想想,网站也是提供数据者),authorites就是他的域名:
下面是在要注册信息
<appli…>
<provider android:name=”.类名” android:authorities=”con.smart.provider.包名”>

</appli>

注意:一旦应用继承了ContentProvider类,后面我们就会把这个应用称为ContentProvider内容提供者

 * ContentProvider来自于文件与数据库都可以
 * 
 * Uri介绍
 * Uri代表了要操作的数据,Uri主要包含了两部信息:1》
 * 需要操作的ContentProvider,2>
 * 对ContentProvider中的,什么数据进行操作, 一个Uri由以下几个部分组成。
 * content:// com.smart.provider.personperovider/person/988
 *  content://  指 scheme  
 *  om.smart.provider.personperovider指 主机名或authority
 *  person  指路径
 *  988  指ID
 * */
public class PersonContentProvider extends ContentProvider {
 // 另一个工程,方问这一个类。

 private DataBaseOpenHelper dbOpenHelper;
 private static final int ALLPERSON = 1;
 private static final int PERSON = 2;
 private static UriMatcher sMatcher = new UriMatcher(UriMatcher.NO_MATCH);// 任何不匹配的时候,返回为-1
 static {
//  
  sMatcher.addURI("com.smart.provider.personprovider", "person",ALLPERSON);
  
  sMatcher.addURI("com.smart.provider.personprovider", "person/#", PERSON);
 }
 //删除
 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  int count = 0;// 返回的行数
  switch (sMatcher.match(uri)) {
  case ALLPERSON:
   count = db.delete("person", selection, selectionArgs);
   break;
  case PERSON:
   long personid = ContentUris.parseId(uri);
   String where = TextUtils.isEmpty(selection) ? "personid=?"
     : selection + " and personid=?";
   String[] params = new String[] { String.valueOf(personid) };
   if (!TextUtils.isEmpty(selection) && selectionArgs != null) {
    params = new String[selectionArgs.length + 1];
    for (int i = 0; i < selectionArgs.length; i++) {
     params[i] = selectionArgs[i];
    }
    params[selectionArgs.length + 1] = String.valueOf(personid);
   }
   count = db.delete("person", where, params);
   break;
  default:
   throw new IllegalArgumentException("Unkow Uri:" + uri);
  }
  return count;
 }
 
 /**
  * public String getType(Uri uri)
  * 方法用于返回URI所代表数据的MIME类型,如果操作的数据发球集合类型,哪么MIME类型
  * 字符串应该以vnd.android.cursor.dir/开头,要得到所有的person记录Uri为,
  * ontent//com.smart.domain/person 哪么返回MIME类型字符串应该为,
  * vnd.android.cursor.item/开头,比如,得到的ID为1的person记录,URI为
  * ontent//com.smart.domain/person/10 ,哪么返回的MIME类型字符串应该为
  * vnd.android.cursor.item/person
  * */
// 操作数据类型
 @Override   //这个方法,不实现也可以的。
 public String getType(Uri uri) {
  switch (sMatcher.match(uri)) {
  case ALLPERSON:
   //多条
   return "vnd.android.cursor.dir/personprovider.person";
  case PERSON:
   //personprovider.person  内容提供表的
   //单条
   return "vnd.android.cursor.item/personprovider.person";
  default:
   throw new IllegalArgumentException("Unkow Uri:" + uri);
  }
 }

 /**
  * UriMatcher类的使用介绍 因为URI代表了要操作的数据,所以我们很经常需要解析URI,并从URI中获得取数据,ANDROID系统
  * 提供了两个用于操作URI的工具类,分别为URIMATCHER和CONTENTURIS。掌握它们的使用,会便于我们的开发工作,
  * URIMATCHER类于匹配URI。它的用法如下。 首先第一步把你需要匹配路径全部给注册上,如下 常量
  * UriMatcher.NO_MATCH表示不匹配任何路径的返回码 Urimatcher sMatcher=new
  * UriMatcher(UriMatcher.NO_MATCH);
  * 如果match()方法匹配content//com.smart.domain/person 路径,返回匹配为1
  * sMatcher.addURI(content//com.smart.domain/person/1);
  * 如果match()方法匹配content//com.smart.domain/person/230 路径,返回匹配为2
  * sMatcher.addURI(content//com.smart.domain/person/#,2); /#为通配符
  * 
  * 这里讲一下,parse方法为任何的一个字符串转换为Uri地址
  * switch(sMatcher.match(Uri.parse("content//com.smart.domain/person/10"))){
  * 
  * }
  * 
  * 
  * 注册完需要匹配的URI后,就可以使用sMatcher.match(Uri)方法对输入进行匹配 ,如果匹配就返回匹配码
  * 匹配码是调用ADDRUI()方法传入第三个参数,假设匹配 content//com.smart.domain/person 路径,返回的匹配码为1
  * 
  * **/
 //增加
 @Override
 public Uri insert(Uri uri, ContentValues values) {
  // 返回的类型为,返回一路径,
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  long id = 0;
  // com.smart.domain/person/100
  switch (sMatcher.match(uri)) {
  case ALLPERSON:
   // com.smart.domain/person/
   id = db.insert("person", "name", values);// 记是记录的行号,主健INT类,就是主健,
   return ContentUris.withAppendedId(uri, id);

  case PERSON:
   // com.smart.domain/person/20
   db.insert("person", "name", values);
   String path = uri.toString();
   // 从0个开始,取到,com.smart.domain/person/20 前面20的一个'/'
   return Uri.parse(path.substring(0, path.lastIndexOf('/')) + id);
  default:
   // 返回一个参数
   throw new IllegalArgumentException("Unkow Uri:" + uri);
  }

 }
 


 @Override
 public boolean onCreate() {
  dbOpenHelper = new DataBaseOpenHelper(this.getContext());
  return true;
 }
//查询
 @Override
 public Cursor query(Uri uri, String[] projection, String selection,
 String[] selectionArgs, String sortOrder) {
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  switch (sMatcher.match(uri)) {
  case ALLPERSON:
  return db.query("person", projection, selection, selectionArgs,null,null,sortOrder);
  case PERSON:
   long personid = ContentUris.parseId(uri);
   String where = TextUtils.isEmpty(selection) ? "personid=?"
     : selection + " and personid=?";
   String[] params = new String[] { String.valueOf(personid) };
   if (!TextUtils.isEmpty(selection) && selectionArgs != null) {
    params = new String[selectionArgs.length + 1];
    for (int i = 0; i < selectionArgs.length; i++) {
     params[i] = selectionArgs[i];
    }
    params[selectionArgs.length + 1] = String.valueOf(personid);
   }
   return db.query("person", projection, where, params,null,null,sortOrder);
  default:
   throw new IllegalArgumentException("Unkow Uri:" + uri);
  }
  
 }
//更新
 @Override
 public int update(Uri uri, ContentValues values, String selection,
   String[] selectionArgs) {
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  int count = 0;// 返回的行数
  switch (sMatcher.match(uri)) {
  case ALLPERSON:
   count = db.update("person", values, selection, selectionArgs);
   break;
  case PERSON://com.smart.domain/100
   long personid = ContentUris.parseId(uri);//得到100的记录
   //判断是否为空,为条件
   String where = TextUtils.isEmpty(selection) ? "personid=?"
     : selection + " and personid=?";
   String[] params = new String[] { String.valueOf(personid) };
   if (!TextUtils.isEmpty(selection) && selectionArgs != null) {
    params = new String[selectionArgs.length + 1];
    for (int i = 0; i < selectionArgs.length; i++) {
     params[i] = selectionArgs[i];
    }
    params[selectionArgs.length + 1] = String.valueOf(personid);
   }
   count = db.update("person", values, where, params);
   break;
  default:
   throw new IllegalArgumentException("Unkow Uri:" + uri);
  }
  return count;
 }
 /*****
  * 增加 ContentUris类用于获取Uri 路径后面的ID部分,它有两个实用的方法,
  * withAppendedld(Uri,id)用于为路径为上ID部分 Uri
  * uri=Uri.parse("content://com.smart.domain/person"); Uri
  * resultUri=ContentUris.withAppendedld(uri,10)
  * 生成后Uri为:content://com.smart.domain/person/10
  * 
  * 更新的方法 parseld(uri)方法用于从路径中获取ID部分 Uri
  * uri=Uri.parse("com.smart.domain/person/10"); long
  * personid=ContentUris.parseld(uri);//获取的结果为10
  * 
  * 
  * **/
}


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.smart.dh"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <uses-library android:name="android.test.runner"/>
       <provider android:name=".PersonContentProvider"
        android:authorities="com.smart.provider.personprovider" 
        android:permission="com.smart.provider.personprovider"/> 
     
        <activity android:name=".DBActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />
 <instrumentation android:name="android.test.InstrumentationTestRunner"
 android:targetPackage="com.smart.dh" android:label="Tests for My App"/>
</manifest> 






   <!--  android:permission="cn.itcast.provider.personprovider"
        这行是指权限    android:permission="com.smart.domain"
        com.smart.domain
        -->



















posted on 2011-03-18 20:24  llb988  阅读(1213)  评论(0编辑  收藏  举报

导航