1. Android 应用程序能够将数据保存到SharedPreference中,也可以保存到文件,SQLite数据库中,甚至任何有效的设备中,但是当你想将你的应用数据与其他的应用共享时,内容提供者就可以发挥作用了。
2. ContentProvider的主要作用:Content provider机制可支持在多个应用中存储和读取数据。这也是跨应用共享数据的唯一方式。在android系统中,没有一个公共的内存区域,供多个应用共享存储数据。
通俗的来说:在Android中,默认使用SQLite作为系统的DB, 但是在Android中,使用方法有点小小的不一样。在Android中每一个应用都运行在各自的进程中,当你的应用需要访问其他应用的数据是,也就需要数据在不同的虚拟机之间传递,这样的情况操作起来可能有些困难。因为在正常情况下,你不能读取其他应用的db文件,ContentProvider正是用来解决在不同应用包之间共享数据的工具。所有被一个Android应用程序创建的偏好设置,文件和数据库都是私有的。为了和其他的应用程序共享数据,应用程序不得不创建一个ContentProvider,去其他的应用程序取数据,他自己的Content Provider必须被调用。Android 本地的Content Provider包括:
CallLog : 地址和接收到的电话信息
Contact.People.Phone : 存储电话号码
Setting.System : 系统设置和偏好设置
Content Provider所提供的函数:
query() insert() update() delete() getType() onCreate()等
下面给出一个例子,让大家更好的了解Content Provider
增删改查实例:
1.创建person库,person表
public class DBOpenHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME="person.db"; //数据库名称
private static final int DATABASE_VERSION =1; //数据库的版本
public DBOpenHelper(Context context){
super(context,DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE person (_id integer primary key autoincrement, name varchar(20), age varchar(10))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS Person");
onCreate(db);
}
}
2. 自定义Content Provider类,实现增删改查
public class PersonProvider extends ContentProvider{
private DBOpenHelper dbOpenHelper;
private static final UriMatcher MATCHER =new UriMatcher(UriMatcher.NO_MATCH);
private static final int PERSONS = 1;
private static final int PERSON = 2;
static {
MATCHER.addURI("cn.com.karl.personProvider","person",PERSONS);
MATCHER.addURI("cn.com.karl.personProvider","person/#",PERSON);
}
@Override
public boolean onCreate(){
this.dbOpenHelper = new DBOpenHelper(this.getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection,String selection,String[] selectionArgs,String sortOrder){
SQLiteDatabase db= dbOpenHelper.getReadableDatabase();
switch(MATCHER.match(uri)){
case PERSONS: //查询所有的时候
return db.query("person",projection,selection,selectionArgs,null,null,sortOrder);
case PERSON: //查询某一id的人的信息
long id=ContentUris.parseId(uri);
String where= "_id="+id;
if(selection != null && !"".equals(selection)){
where = selection +"and"+ where;
}
return db.query("person",projection,where,selectionArgs,null,null,sortOrder);
default:
throw new IllegalArgumentException("UnKwon Uri:"+uri.toString());
}
}
//返回数据的MIME类型
@Override
public String getType(Uri uri){
switch(MATCHER.match(uri)){
case PERSONS:
return "vnd.android.cursor.dir/person";
case PERSON:
return "vnd.android.cursor.item/person";
default:
throw new IllegalArgumentException("Unkwon Uri:"+uri.toString());
}
}
// 插入person表中的所有记录 /person
// 插入person表中指定id的记录 /person/10
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
switch (MATCHER.match(uri)) {
case PERSONS:
// 特别说一下第二个参数是当name字段为空时,将自动插入一个NULL。
long rowid = db.insert("person", "name", values);
Uri insertUri = ContentUris.withAppendedId(uri, rowid);// 得到代表新增记录的Uri
this.getContext().getContentResolver().notifyChange(uri, null);
return insertUri;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case PERSONS:
count = db.delete("person", selection, selectionArgs);
return count;
case PERSON:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = selection + " and " + where;
}
count = db.delete("person", where, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
int count = 0;
switch (MATCHER.match(uri)) {
case PERSONS:
count = db.update("person", values, selection, selectionArgs);
return count;
case PERSON:
long id = ContentUris.parseId(uri);
String where = "_id=" + id;
if (selection != null && !"".equals(selection)) {
where = selection + " and " + where;
}
count = db.update("person", values, where, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
}
}
}
3.实现的时候的Activity类
public class ResolverDemoActivity extends Activity {
/** Called when the activity is first created. */
private SimpleCursorAdapter adapter;
private ListView listView;
private Button button_insert;
private Button button_query;
private Button button_query_one;
private EditText edittext_query;
private Button button_update_one;
private EditText edittext_update;
private Button button_update;
private Button button_delete;
private Button button_delete_one;
private EditText edittext_delete;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView=(ListView) this.findViewById(R.id.listView);
ContentResolver contentResolver = getContentResolver();
Uri selectUri = Uri.parse("content://cn.com.karl.personProvider/person");
Cursor cursor=contentResolver.query(selectUri, null, null, null, null);
adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,
new String[]{"_id", "name", "age"}, new int[]{R.id.id, R.id.name, R.id.age});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListView lView = (ListView)parent;
Cursor data = (Cursor)lView.getItemAtPosition(position);
int _id = data.getInt(data.getColumnIndex("_id"));
Toast.makeText(ResolverDemoActivity.this, _id+"", 1).show();
}
});
button_insert = (Button) this.findViewById(R.id.insertbutton);
button_insert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ContentResolver contentResolver = getContentResolver();
Uri insertUri = Uri.parse("content://cn.com.karl.personProvider/person");
ContentValues values = new ContentValues();
values.put("name", "wangkuifeng");
values.put("age", 23);
Uri uri = contentResolver.insert(insertUri, values);
Toast.makeText(ResolverDemoActivity.this, "添加完成", 1).show();
}
});
button_query = (Button)this.findViewById(R.id.querybutton);
button_query.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentResolver contentResolver = getContentResolver();
Uri selectUri = Uri.parse("content://cn.com.karl.personProvider/person");
Cursor cursor=contentResolver.query(selectUri, null, null, null, null);
SimpleCursorAdapter adapter= new SimpleCursorAdapter(ResolverDemoActivity.this, R.layout.item, cursor,
new String[]{"_id", "name", "age"}, new int[]{R.id.id, R.id.name, R.id.age});
listView.setAdapter(adapter);
Toast.makeText(ResolverDemoActivity.this, "查询完成", 1).show();
}
});
button_query_one = (Button)this.findViewById(R.id.queryonebutton);
edittext_query = (EditText)this.findViewById(R.id.queryone_et);
button_query_one.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String num = edittext_query.getText().toString();
ContentResolver contentResolver = getContentResolver();
Uri selectUri = Uri.parse("content://cn.com.karl.personProvider/person"+"/"+num);
Cursor cursor=contentResolver.query(selectUri, null, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(ResolverDemoActivity.this, R.layout.item, cursor,
new String[]{"_id", "name", "age"}, new int[]{R.id.id, R.id.name, R.id.age});
listView.setAdapter(adapter);
Toast.makeText(ResolverDemoActivity.this, "查询完成", 1).show();
}
});
edittext_update = (EditText)this.findViewById(R.id.update_et);
button_update_one = (Button)this.findViewById(R.id.updateonebutton);
button_update_one.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String num = edittext_update.getText().toString();
ContentResolver contentResolver = getContentResolver();
Uri updateUri = Uri.parse("content://cn.com.karl.personProvider/person"+"/"+num);
ContentValues values = new ContentValues();
values.put("name", "superjunjin");
values.put("age", 26);
int count = contentResolver.update(updateUri, values, null, null);
Toast.makeText(ResolverDemoActivity.this, "更新完成", 1).show();
}
});
button_update = (Button)this.findViewById(R.id.updatebutton);
button_update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentResolver contentResolver = getContentResolver();
Uri updateUri = Uri.parse("content://cn.com.karl.personProvider/person");
ContentValues values = new ContentValues();
values.put("name", "superjunjin");
values.put("age", 26);
int count = contentResolver.update(updateUri, values, null, null);
Toast.makeText(ResolverDemoActivity.this, "更新完成", 1).show();
}
});
button_delete = (Button)this.findViewById(R.id.deletebutton);
button_delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ContentResolver contentResolver = getContentResolver();
Uri deleteUri = Uri.parse("content://cn.com.karl.personProvider/person");
contentResolver.delete(deleteUri, null, null);
Toast.makeText(ResolverDemoActivity.this, "删除完成", 1).show();
}
});
edittext_delete = (EditText)this.findViewById(R.id.delete_et);
button_delete_one = (Button)this.findViewById(R.id.deleteonebutton);
button_delete_one.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String num = edittext_delete.getText().toString();
ContentResolver contentResolver = getContentResolver();
Uri deleteUri = Uri.parse("content://cn.com.karl.personProvider/person"+"/"+num);
contentResolver.delete(deleteUri, null, null);
Toast.makeText(ResolverDemoActivity.this, "删除完成", 1).show();
}
});
}
}