1、新建继承ContentProvider的类
package com.wangzhu.demo; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; public class MyContentProvider extends ContentProvider { /** * ContentProvider的数据访问路径 */ public static final Uri URI = Uri.parse("content://com.wangzhu.provider"); private SQLiteDatabase database; @Override public int delete(Uri arg0, String arg1, String[] arg2) { return 0; } @Override public String getType(Uri arg0) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { database.insert("tab", "_id", values); return null; } @Override public boolean onCreate() { database = getContext().openOrCreateDatabase("myProvider.db3", Context.MODE_PRIVATE, null); database.execSQL("create table IF NOT EXISTS tab(_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL)"); return true; } @Override public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4) { Cursor cursor = database.query("tab", null, null, null, null, null, null); return cursor; } @Override public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) { return 0; } }
2、在AndroidManifest.xml中为应用程序添加ContentProvider的访问权限
<!-- android:exported设置为true,表示其他应用可以访问,否则不可以访问 --> <provider android:name="MyContentProvider" android:authorities="com.wangzhu.provider" android:exported="true" > </provider>
3、进行插入与查询
final Uri uri = MyContentProvider.URI; /** * 往Provider中写入数据 */ protected void write() { //使用getContentResolver()方法获取ContentResolver对象 ContentResolver resolver = getContentResolver(); ContentValues values = null; values = new ContentValues(); values.put("name", "Java"); //调用ContentResolver对象的insert方法,插入数据 resolver.insert(uri, values); values = new ContentValues(); values.put("name", "Swift"); resolver.insert(uri, values); values = new ContentValues(); values.put("name", "Python"); resolver.insert(uri, values); values = new ContentValues(); values.put("name", "C#"); resolver.insert(uri, values); } /** * 读取Provider中的内容 */ protected void read() { StringBuilder accum = new StringBuilder(); //使用getContentResolver()方法获取ContentResolver对象 //调用ContentResolver对象的query方法,查询数据,返回Cursor对象 Cursor cursor = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); for (int i = 0, count = cursor.getCount(); i < count; i++) { accum.append(cursor.getString(cursor.getColumnIndex("name"))) .append(" "); cursor.moveToNext(); } System.err.println("read: " + accum); }