您的位置:首页 > 其它

访问内容提供者(和上文联系),测试

2015-11-25 19:50 274 查看
内容提供者提供了对自定义的一个SQLite数据库的表person中增删改查,对象为person(bean)

public class TestPersonContentProvider extends AndroidTestCase

{

  private static final String TAG = "TestPersonContentProvider";

  public void testInsert()

  {

    //访问地址:content://要访问的包名.类名/person/insert

    ContentResolver resolver = getContext().getContentResolver(); //内容提供者的访问类

    ContentValues values = new ContentValues();

    values.put("name", "sz");

    values.put("age", "20");

    resolver.insert(Uri.parse("content://要访问的包名.类名/person/insert"), values);

  }

  public void testUpdate()

  {

    ContentResolver resolver = getContext().getContentResolver(); //内容提供者的访问类

    ContentValues values = new ContentValues();

    values.put("name", "1505");

    String where = "id = ?";

    String[] selectionArgs = new String[]{"1"};

    int id = resolver.update(

    Uri.parse("content://要访问的包名.类名/person/update"),

    values ,

    where,

    selectionArgs);

    Log.d(TAG, "UPDATE .... = " + id);

  }

  public void testQuery()

  {

    ContentResolver resolver = getContext().getContentResolver(); //内容提供者的访问类

    //content://要访问的包名.类名/person/query

    String[] projection = new String[]{"id","name","age"};

    Cursor cursor = resolver.query(

    Uri.parse("content://要访问的包名.类名/person/query"),

    projection,

    null,

    null,

    null);

    if(null != cursor && cursor.getCount() > 0)

    {

      while(cursor.moveToNext())

      {

        Integer id = cursor.getInt(0);

        String name = cursor.getString(1);

        Integer age = cursor.getInt(2);

        Log.d(TAG, "id=" + id + " name= " + name + " age= " + age);

      }

      cursor.close(); // 一定记住不要忘了关闭游标

    }

  }

}

注意权限:与内容提供者中想对应的权限

<uses-permission android:name="aaa.bbb.ccc"/>

<uses-permission android:name="aaa.bbb.ccc.ddd"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: