ContentProvider详解

作用:把一个App中的数据库通过Url的形式共享出来,供其他App使用。

首先在App1中创建一个数据库,用SQLiteOpenHelper

 public class MyOpenHelper extends SQLiteOpenHelper {

     public MyOpenHelper(Context context){
         super(context,"Account.db",null,1);
     }
     @Override
     public void onCreate(SQLiteDatabase db) {
         db.execSQL("create table info(_id integer primary key autoincrement, name varchar(20),money varchar(10))");
         db.execSQL("insert into info(name, money) values(?,?)",new String[]{"张三","5000"});
         ContentValues cv = new ContentValues();
         cv.put("name","李四");
         cv.put("money","6000");
         db.insert("info",null,cv);
     }
     @Override
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     }
 }

创建数据库:

 MyOpenHelper myOpenHelper = new MyOpenHelper(this);
 myOpenHelper.getReadableDatabase();

然后用过ContentProvider把数据库共享出来,首先看代码:

public class MyProvider extends ContentProvider {
    //定义一个Uri路径匹配器   (匹配不成功的时候会返回一个NO_MATCH返回一个-1)
    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int QUERYSUCESS = 0;
    private static final int INSERTSUCESS = 1;
    private static final int UPADTESUCESS = 2;
    private static final int DELETESUCESS = 3;
    //创建一个静态代码块,在这里添加Uri
    static {
        /**
         * authority 注意:和清单文件里面定义的一样 com.coderwei.provider/query
         */
        sURIMatcher.addURI("com.coderwei.provider","query",QUERYSUCESS );
        sURIMatcher.addURI("com.coderwei.provider","insert",INSERTSUCESS );
        sURIMatcher.addURI("com.coderwei.provider","update",UPADTESUCESS );
        sURIMatcher.addURI("com.coderwei.provider","delete",DELETESUCESS );
    }

    private MyOpenHelper myOpenHelper;

    @Override
    public boolean onCreate() {
        //初始化MyOpenHelper
        myOpenHelper = new MyOpenHelper(getContext());
        return false;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        if (sURIMatcher.match(uri)==QUERYSUCESS){
            //说明路径匹配成功
            SQLiteDatabase db = myOpenHelper.getReadableDatabase();
            Cursor cursor = db.query("info",projection,selection,selectionArgs,null,null,sortOrder);
            //db.close();
            //这里不能关闭Cursor
            return cursor;
        }else {
            throw  new IllegalArgumentException("uri路径不匹配");
        }
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if (sURIMatcher.match(uri)==INSERTSUCESS){
            SQLiteDatabase db = myOpenHelper.getReadableDatabase();
            long insert = db.insert("info",null,values);
            Uri uri1 = Uri.parse("com.coderwei.insert/"+insert);
            //db.close();
            return uri1;
        }else {
            throw  new IllegalArgumentException("uri路径不匹配");
        }
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        if (sURIMatcher.match(uri)==DELETESUCESS){
            SQLiteDatabase db = myOpenHelper.getReadableDatabase();
            int delete = db.delete("info",selection,selectionArgs);
            //db.close();
            return delete;
        }else {
            throw  new IllegalArgumentException("uri路径不匹配");
        }
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        if (sURIMatcher.match(uri)== UPADTESUCESS){
            SQLiteDatabase db = myOpenHelper.getReadableDatabase();
            int update = db.update("info",values,selection,selectionArgs);
            //db.close();
            return update;
        }else {
            throw  new IllegalArgumentException("uri路径不匹配");
        }
    }
}

代码很长,但是很简单,主要把上面四个增删改查方法实现就行,上面的db.close()关闭的时候报错了,所以就注释掉了,关不关都可以。

Insert方法返回的是一个Url对象,直接自己写一个就行了。

记得在Manifest.xml中配置ContentProvider:

<provider
            android:authorities="com.coderwei.provider"
            android:exported="true"
            android:name=".MyProvider">
 </provider>
android:authorities  自己随便给一个字符串,
android:exported="true"一定要写上这句,这句话表示可以被另一个Application的组件启动,没写可能会报错。
sURIMatcher.addURI("com.coderwei.provider","query",QUERYSUCESS );中的com.coderwei.provider就是这个字符串。

然后就是来到App2了,先看代码:
 public class MainActivity extends Activity  {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
     }
     public void click1(View v){
         doQuery();
     }
     public void click2(View v){
         doInsert();
     }
     public void click3(View v){
         doDelete();
     }
     public void click4(View v){
         doUpdate();
     }

     private void doQuery(){
         Uri uri = Uri.parse("content://com.coderwei.provider/query");
         Cursor cursor = getContentResolver().query(uri,new String[]{"name","money"},null,null,null);

         if (cursor!=null){
             while (cursor.moveToNext()){
                 String name = cursor.getString(0);
                 String money = cursor.getString(1);
                 System.out.println("name:"+name+"  money: "+money);
             }
         }
     }

     private void doInsert(){
         Uri uri = Uri.parse("content://com.coderwei.provider/insert");
         ContentValues cv = new ContentValues();
         cv.put("name","王五");
         cv.put("money","800");
         Uri uri1 = getContentResolver().insert(uri,cv);
         System.out.println("插入uri1:"+uri1);
     }

     private void doDelete(){
         Uri uri = Uri.parse("content://com.coderwei.provider/delete");
         int delete = getContentResolver().delete(uri,"name=?",new String[]{"王五"});
         System.out.print("刪除了: "+delete);
     }

     private void doUpdate(){
         Uri uri = Uri.parse("content://com.coderwei.provider/update");
         ContentValues cv = new ContentValues();
         cv.put("money","9000");
         int update = getContentResolver().update(uri,cv,"name=?",new String[]{"王五"});
         System.out.println("更新了:"+update);
     }
 }

里面就是四个增删改查方法,就Query稍微麻烦一点,查询的结果返回一个Cursor对象,然后把这个Cursor对象的内容取出来就行了,



上一篇:Android--解析XML之SAX


下一篇:elasticsearch java客户端api使用(一)