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 ); } }
复制代码
ContentProviderAndroid 的一种组件,它提供了一个标准的接口,允许应用程序在不同的进程之间共享数据。下面是一个简单的 ContentProvider 示例,用于提供用户信息: 1. 创建一个 User 类,代表用户信息: ```java public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } ``` 2. 创建一个 UserProvider 类,继承自 ContentProvider,并实现必要的方法: ```java public class UserProvider extends ContentProvider { private static final String AUTHORITY = "com.example.userprovider"; private static final String BASE_PATH = "users"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); private List<User> users; @Override public boolean onCreate() { users = new ArrayList<>(); users.add(new User("Alice", 25)); users.add(new User("Bob", 30)); return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { MatrixCursor cursor = new MatrixCursor(new String[]{"_id", "name", "age"}); int id = 0; for (User user : users) { cursor.addRow(new Object[]{id++, user.getName(), user.getAge()}); } return cursor; } @Nullable @Override public String getType(@NonNull Uri uri) { return "vnd.android.cursor.dir/vnd.example.users"; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { String name = values.getAsString("name"); int age = values.getAsInteger("age"); users.add(new User(name, age)); return CONTENT_URI; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { users.clear(); return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { String name = values.getAsString("name"); int age = values.getAsInteger("age"); users.clear(); users.add(new User(name, age)); return 1; } @Override public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) { for (ContentValues value : values) { String name = value.getAsString("name"); int age = value.getAsInteger("age"); users.add(new User(name, age)); } return values.length; } } ``` 3. 在 AndroidManifest.xml 声明 ContentProvider: ```xml <provider android:name=".UserProvider" android:authorities="com.example.userprovider" android:exported="true"/> ``` 4. 在应用程序使用 ContentProvider: ```java ContentResolver resolver = getContentResolver(); Uri uri = UserProvider.CONTENT_URI; // 查询所有用户信息 Cursor cursor = resolver.query(uri, null, null, null, null); while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.d(TAG, "name: " + name + ", age: " + age); } // 插入一个新用户 ContentValues values = new ContentValues(); values.put("name", "Charlie"); values.put("age", 35); resolver.insert(uri, values); // 更新第一个用户信息 ContentValues updateValues = new ContentValues(); updateValues.put("name", "Alice"); updateValues.put("age", 26); resolver.update(ContentUris.withAppendedId(uri, 0), updateValues, null, null); ``` 以上就是一个简单的 ContentProvider 示例。通过 ContentProvider,我们可以在不同的应用程序共享数据,从而提高应用程序之间的互操作性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值