ContentProvider主要是提供了我们访问数据的统一接口,一旦一个类继承了ContengProvider,我们就会称这个应用程序为ContengProvider(内容提供者)
使用ContentProvider的步骤:
1、写一个类继承ContentProvider,并改写其中的一些方法。
2、在AndroidManifest.xml文件中声明你所定义的provider
在使用ContentProvider之前先要了解两个类的使用:
UriMatcher:
UriMatcher类用于匹配Uri,它的用法如下:
首先第一步把你需要匹配Uri路径全部给注册上,如下:
//
常量
UriMatcher.NO_MATCH
表示不匹配任何路径的返回码
UriMatcher sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//
如果
match()
方法匹配
content://cn.itcast.provider.personprovider/person
路径,返回匹配码为
1
sMatcher.addURI(
“
cn.itcast.provider.personprovider
”
,
“
person
”
, 1);//
添加需要匹配
uri
,如果匹配就会返回匹配码
//
如果
match()
方法匹配
content://cn.itcast.provider.personprovider/person/230
路径,返回匹配码为
2
sMatcher.addURI(“cn.itcast.provider.personprovider”, “person/#”, 2);
//#
号为通配符
ContentUris:
ContentUris类用于获取Uri路径后面的ID部分,它有两个比较实用的方法:
withAppendedId(uri, id)用于为路径加上ID部分:
Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person")
Uri resultUri = ContentUris.withAppendedId(uri, 10);
//
生成后的
Uri
为:
content://cn.itcast.provid
er.personprovider/person/10
parseId(uri)方法用于从路径中获取ID部分:
Uri uri = Uri.parse("content://cn.itcast.provider.personprovider/person/10")
long personid = ContentUris.parseId(uri);//
获取的结果为
:10
下面开始使用ContentProvider:
1、定义一个类,继承SQLiteOpenHelper
- public class MyDBHelper extends SQLiteOpenHelper
- {
- public static final int VERSION=1;
- public static final String DB_NAME="gjun";
- public MyDBHelper(Context context)
- {
- super(context, DB_NAME, null, VERSION);
- // TODO Auto-generated constructor stub
- }
- @Override
- public void onCreate(SQLiteDatabase db)
- {
- // TODO Auto-generated method stub
- //通常在此创建数据库中的表
- db.execSQL("create table student(id integer primary key autoincrement,name varchar(20))");
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
- {
- // TODO Auto-generated method stub
- }
- }
2、定义一个类,继承了ContentProvider
- public class MyProvider extends ContentProvider
- {
- private MyDBHelper helper;
- private SQLiteDatabase db;
- private static final String AUTHORI="com.provider.db.myprovider";
- private static final int ITEM=1;
- private static final int ITEMS=2;
- private static final String CONTENT_URI="content://com.provider.db.myprovider";
- private static final UriMatcher matcher;
- static
- {
- matcher=new UriMatcher(UriMatcher.NO_MATCH);
- matcher.addURI(AUTHORI,"student",ITEMS);
- matcher.addURI(AUTHORI,"student/#",ITEM);
- }
- @Override
- public int delete(Uri uri, String selection, String[] selectionArgs)
- {
- // TODO Auto-generated method stub
- switch(matcher.match(uri))
- {
- case ITEM:
- int num=0;
- StringBuilder sb=new StringBuilder();
- long id=ContentUris.parseId(uri);
- sb.append("id="+id);
- db=helper.getWritableDatabase();
- if(selection!=null && !selection.equals(""))
- {
- sb.append(" and selection");
- }
- num=db.delete("student",sb.toString(),selectionArgs);
- return num;
- case ITEMS:
- db=helper.getWritableDatabase();
- num=db.delete("student", selection,selectionArgs);
- return num;
- default:
- throw new IllegalArgumentException("UnKnow Uri:"+uri.toString());
- }
- }
- @Override
- public String getType(Uri uri)
- {
- // TODO Auto-generated method stub
- switch(matcher.match(uri))
- {
- case ITEM:
- return "vnd.android.cursor.item/student";
- case ITEMS:
- return "vnd.android.cursor.dir/student";
- default:
- throw new IllegalArgumentException("UnKnow URI:"+uri.toString());
- }
- }
- @Override
- public Uri insert(Uri uri, ContentValues values)
- {
- // TODO Auto-generated method stub
- long id=0;
- Uri result=null;
- switch(matcher.match(uri))
- {
- case ITEM:
- db=helper.getWritableDatabase();
- id=db.insert("student", null, values);
- result=Uri.parse(uri.toString().substring(0, uri.toString().lastIndexOf("/")+1));
- ContentUris.withAppendedId(result, id);
- return result;
- case ITEMS:
- db=helper.getWritableDatabase();
- id=db.insert("student", null, values);
- result=ContentUris.withAppendedId(uri, id);
- return result;
- default:
- throw new IllegalArgumentException("UnKnow URI:"+uri.toString());
- }
- }
- @Override
- public boolean onCreate()
- {
- // TODO Auto-generated method stub
- helper=new MyDBHelper(this.getContext());
- return true;
- }
- @Override
- public Cursor query(Uri uri, String[] projection, String selection,
- String[] selectionArgs, String sortOrder)
- {
- // TODO Auto-generated method stub
- db=helper.getReadableDatabase();
- Cursor cursor=null;
- switch(matcher.match(uri))
- {
- case ITEM:
- StringBuilder sb=new StringBuilder();
- long id=ContentUris.parseId(uri);
- sb.append("id="+id);
- if(selection!=null && selection.equals(""))
- {
- sb.append("and selection");
- }
- cursor=db.query("student", projection, sb.toString(), selectionArgs,null, null,sortOrder);
- return cursor;
- case ITEMS:
- return db.query("student", projection, selection, selectionArgs, null, null, sortOrder);
- default:
- throw new IllegalArgumentException("UnKnow URI:"+uri.toString());
- }
- }
- @Override
- public int update(Uri uri, ContentValues values, String selection,
- String[] selectionArgs)
- {
- // TODO Auto-generated method stub
- db=helper.getWritableDatabase();
- int num=0;
- switch(matcher.match(uri))
- {
- case ITEM:
- StringBuilder sb=new StringBuilder();
- long id=ContentUris.parseId(uri);
- sb.append("id="+id);
- if(selection!=null && selection.equals(""))
- {
- sb.append("and selection");
- }
- num=db.update("student", values, sb.toString(), selectionArgs);
- return num;
- case ITEMS:
- num=db.update("student", values, selection, selectionArgs);
- return num;
- default:
- throw new IllegalArgumentException("UnKnow URI:"+uri.toString());
- }
- }
- }
3、编写一个测试类
- public class MainActivity extends Activity implements OnClickListener
- {
- /** Called when the activity is first created. */
- private Button btnadd=null;
- private Button btnadds=null;
- private Button btndel=null;
- private Button btndels=null;
- private Button btnupdate=null;
- private Button btnupdates=null;
- private Button btnfind=null;
- private Button btnfinds=null;
- private ContentResolver resolver=null;
- private Uri uri=Uri.parse("content://com.provider.db.myprovider/student");
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- init();
- initListener();
- resolver=this.getContentResolver();
- }
- public void init()
- {
- btnadd=(Button)this.findViewById(R.id.btnadd);
- btnadds=(Button)this.findViewById(R.id.btnadds);
- btndel=(Button)this.findViewById(R.id.btndel);
- btndels=(Button)this.findViewById(R.id.btndels);
- btnupdate=(Button)this.findViewById(R.id.btnupdate);
- btnupdates=(Button)this.findViewById(R.id.btnupdates);
- btnfind=(Button)this.findViewById(R.id.btnfind);
- btnfinds=(Button)this.findViewById(R.id.btnfinds);
- }
- public void initListener()
- {
- btnadd.setOnClickListener(this);
- btnadds.setOnClickListener(this);
- btndel.setOnClickListener(this);
- btndels.setOnClickListener(this);
- btnupdate.setOnClickListener(this);
- btnupdates.setOnClickListener(this);
- btnfind.setOnClickListener(this);
- btnfinds.setOnClickListener(this);
- }
- @Override
- public void onClick(View v)
- {
- // TODO Auto-generated method stub
- Uri nowuri=null;
- if(v.getId()==R.id.btnadd)
- {
- nowuri=ContentUris.withAppendedId(uri, 1);
- ContentValues cv=new ContentValues();
- cv.put("name", "gavin");
- resolver.insert(nowuri,cv);
- Toast.makeText(this, "添加用戶成功!",Toast.LENGTH_SHORT).show();
- }else if(v.getId()==R.id.btnadds)
- {
- ContentValues cv=new ContentValues();
- cv.put("name", "tom");
- resolver.insert(uri,cv);
- Toast.makeText(this, "添加用戶成功!",Toast.LENGTH_SHORT).show();
- }else if(v.getId()==R.id.btndel)
- {
- nowuri=ContentUris.withAppendedId(uri, 1);
- resolver.delete(nowuri, null, null);
- Toast.makeText(this, "刪除單個用戶成功!!",Toast.LENGTH_SHORT).show();
- }else if(v.getId()==R.id.btndels)
- {
- resolver.delete(uri, null, null);
- Toast.makeText(this, "刪除所有用戶成功!!",Toast.LENGTH_SHORT).show();
- }else if(v.getId()==R.id.btnfind)
- {
- nowuri=ContentUris.withAppendedId(uri, 6);
- Cursor cursor=resolver.query(nowuri, null, null, null, null);
- cursor.moveToFirst();
- int id=cursor.getInt(cursor.getColumnIndex("id"));
- String name=cursor.getString(cursor.getColumnIndex("name"));
- Toast.makeText(this, "id"+id+" name"+name,Toast.LENGTH_SHORT).show();
- }else if(v.getId()==R.id.btnfinds)
- {
- Cursor cursor=resolver.query(uri, null, null, null, null);
- cursor.move(2);
- int id=cursor.getInt(cursor.getColumnIndex("id"));
- String name=cursor.getString(cursor.getColumnIndex("name"));
- Toast.makeText(this, "id"+id+" name"+name,Toast.LENGTH_SHORT).show();
- }else if(v.getId()==R.id.btnupdate)
- {
- nowuri=ContentUris.withAppendedId(uri, 6);
- ContentValues cv=new ContentValues();
- cv.put("name", "jack");
- resolver.update(nowuri,cv,null,null);
- }else if(v.getId()==R.id.btnupdates)
- {
- ContentValues cv=new ContentValues();
- cv.put("name", "jack");
- resolver.update(uri,cv,null,null);
- }
- }
- }