标签:
使用ContentProvider共享数据
当应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。虽然使用其他方法也可以对外共享数据,但数据访问方式会因数据存储的方式而不同,如:采用文件方式对外共享数据,需要进行文件操作读写数据;采用sharedpreferences共享数据,需要使用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)
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
public String getType(Uri uri)}
第二步需要在AndroidManifest.xml使用<provider>对该ContentProvider进行配置,为了能让其他应用找到该ContentProvider , ContentProvider 采用了authorities(主机名/域名)对它进行唯一标识,你可以把 ContentProvider看作是一个网站(想想,网站也是提供数据者),authorities 就是他的域名:
<manifest .... >
<application android:icon="@drawable/icon" android:label="@string/app_name">
<provider android:name=".PersonContentProvider" android:authorities="com.jbridge.provider.personprovider"/>
</application>
</manifest>
注意:一旦应用继承了ContentProvider类,后面我们就会把这个应用称为ContentProvider(内容提供者)。
Uri介绍
Uri代表了要操作的数据,Uri主要包含了两部分信息:1》需要操作的ContentProvider ,2》对ContentProvider中的什么数据进行操作,一个Uri由以下几部分组成:
ContentProvider示例程序
我们为《Android之SQlite存储》示例程序添加一个ContentProvider,供其他应用来访问我们的数据。
1.为SQLite示例程序添加ContentProvider类
package com.jbridge.db; import com.jbridge.service.DataBaseOpenHelper; 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; public class PersonContentProvider extends ContentProvider { private DataBaseOpenHelper dbOpenHelper; private static final int ALLPERSON = 1; private static final int PERSON = 2; private static final UriMatcher sMatcher = new UriMatcher( UriMatcher.NO_MATCH); static { sMatcher.addURI("com.jbridge.provider.personprovider", "person", ALLPERSON); sMatcher.addURI("com.jbridge.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:// com.jbridge.provider.personprovider/person count=db.delete("person", selection,selectionArgs); break; case PERSON:// com.jbridge.provider.personprovider/person/10 long personid=ContentUris.parseId(uri); //防止他输入时String selection, String[] selectionArgs参数为空,这样就会修改表的所有数据了 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]=String.valueOf(personid); } count = db.delete("person", where,params); break; default: throw new IllegalArgumentException("Unknow Uri:" + uri); } return count; } @Override public String getType(Uri uri) { switch (sMatcher.match(uri)) { case ALLPERSON:// //数据集的MIME类型字符串则应该以vnd.android.cursor.dir/开头 return "vnd.android.cursor.dir/personprovider.person"; case PERSON://单一数据的MIME类型字符串应该以vnd.android.cursor.item/开头 return "vnd.android.cursor.item/personprovider.person"; default: throw new IllegalArgumentException("Unknow Uri:" + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); long id = 0; switch (sMatcher.match(uri)) { case ALLPERSON:// com.jbridge.provider.personprovider/person id = db.insert("person", "name", values);// 返回值是记录的行号,主键为int实际上就是主键值,主键为text则为行号 return ContentUris.withAppendedId(uri, id); case PERSON:// com.jbridge.provider.personprovider/person/10 id = db.insert("person", "name", values);// 返回值是记录的行号,主键为int实际上就是主键值,主键为text则为行号 String path = uri.toString(); return Uri.parse(path.substring(0, path.lastIndexOf("/")) + id); default: throw new IllegalArgumentException("Unknow Uri:" + uri); } } @Override public boolean onCreate() { dbOpenHelper=new DataBaseOpenHelper(this.getContext()); return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); switch (sMatcher.match(uri)) { case ALLPERSON:// com.jbridge.provider.personprovider/person return db.query("person",projection, selection, selectionArgs,null, null, sortOrder); case PERSON:// com.jbridge.provider.personprovider/person/10 long personid=ContentUris.parseId(uri); //防止他输入时String selection, String[] selectionArgs参数为空,这样就会修改表的所有数据了 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]=String.valueOf(personid); } return db.query("person",projection, where, params,null, null, sortOrder); default: throw new IllegalArgumentException("Unknow 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:// com.jbridge.provider.personprovider/person count = db.update("person", values, selection,selectionArgs); break; case PERSON:// com.jbridge.provider.personprovider/person/10 long personid=ContentUris.parseId(uri); //防止他输入时String selection, String[] selectionArgs参数为空,这样就会修改表的所有数据了 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]=String.valueOf(personid); } count = db.update("person", values, where,params); break; default: throw new IllegalArgumentException("Unknow Uri:" + uri); } return count; } }
2.添加ContentProvider配置
<provider android:name=".PersonContentProvider" android:authorities="com.jbridge.provider.personprovider" android:permission="android.permission.READ_PERSON_DB"/> |
3.测试SQLite示例程序的ContentProvider,建立项目contentProviderUser
Project name: contentProviderUser
BuildTarget:Android2.2
Application name: 内容使用者
Package name: com.jbridge.user
Create Activity: ContentProviderUserActivity
Min SDK Version:8
package com.jbridge.user; import android.R.string; 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 ContentProviderUserActivity extends Activity { private static final String TAG="ContentProviderUserActivity"; /* @Override //向数据库插入数据 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ContentResolver contentResolver=this.getContentResolver(); Uri uri=Uri.parse("content://com.jbridge.provider.personprovider/person"); ContentValues values=new ContentValues(); values.put("name", "刘德华"); values.put("age",(short)55); contentResolver.insert(uri, values); }*/ /* @Override //向数据库修改数据 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ContentResolver contentResolver=this.getContentResolver(); Uri uri=Uri.parse("content://com.jbridge.provider.personprovider/person/4"); ContentValues values=new ContentValues(); values.put("name", "haha"); values.put("age",(short)55); contentResolver.update(uri, values, null, null); }*/ /*@Override //向数据库删除数据 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ContentResolver contentResolver=this.getContentResolver(); Uri uri=Uri.parse("content://com.jbridge.provider.personprovider/person"); contentResolver.delete(uri, "personid>?",new String[]{String.valueOf(18)} ); // contentResolver.delete(uri,null,null ); }*/ /*@Override //向数据库查询数据 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ContentResolver contentResolver=this.getContentResolver(); Uri uri=Uri.parse("content://com.jbridge.provider.personprovider/person"); Cursor cursor=contentResolver.query(uri, new String[]{"personid","name","age"}, null, null, "personid desc"); while (cursor.moveToNext()) { Log.i(TAG, "personid "+cursor.getInt(0)); } cursor.close(); }*/ @Override //向电话本取得数据 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); 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=contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+contactID,null, null); StringBuilder sb=new StringBuilder(); while (phones.moveToNext()) { String phoneNumber=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); sb.append(phoneNumber).append(","); } sb.deleteCharAt(sb.lastIndexOf(",")); phones.close(); Log.i(TAG, sb.toString()); Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactID, null, null); while (emails.moveToNext()) { // This would allow you get several email addresses String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); Log.i(TAG, "emailAddress="+ emailAddress); } emails.close(); cursor.close(); } } }
Android内容提供者(Content provider)
标签:
原文地址:http://www.cnblogs.com/liaolandemengxiang/p/4326151.html