使用ContentResolver操作ContentProvider中的数据
ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver类来完成,要获取ContentResolver对象,可以使用Activity提供的getContentResolver()方法。 ContentResolver 类提供了与ContentProvider类相同签名的四个方法:public Uri insert(Uri uri, ContentValues values)该方法用于往ContentProvider添加数据。public int delete(Uri uri, String selection, String[] selectionArgs)该方法用于从ContentProvider删除数据。public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)该方法用于更新ContentProvider中的数据。public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)该方法用于从ContentProvider中获取数据。这些方法的第一个参数为Uri,代表要操作的是哪个ContentProvider和对其中的什么数据进行操作,假设给定的是:Uri.parse(“content://cn.itcast.provider.personprovider/person/10”),那么将会对主机名为cn.itcast.provider.personprovider的ContentProvider进行操作,操作的数据为person表中id为10的记录。------------------------------------------------------------------------------------------------------------------------ContentResolver对ContentProvider中的数据进行添加、删除、修改和查询操作:ContentResolver resolver = getContentResolver();Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person");//添加一条记录ContentValues values = new ContentValues();values.put("name", "itcast");values.put("age", 25);resolver.insert(uri, values);//获取person表中所有记录Cursor cursor = resolver.query(uri, null, null, null, "personid desc");while(cursor.moveToNext()){Log.i("ContentTest", "personid="+ cursor.getInt(0)+ ",name="+ cursor.getString(1));}//把id为1的记录的name字段值更改新为limingContentValues updateValues = new ContentValues();updateValues.put("name", "liming");Uri updateIdUri = ContentUris.withAppendedId(uri, 2);resolver.update(updateIdUri, updateValues, null, null);//删除id为2的记录Uri deleteIdUri = ContentUris.withAppendedId(uri, 2);resolver.delete(deleteIdUri, null, null);