模拟2个应用之间使用contentprovider。
package com.example.contentprovider;
import android.net.Uri;
public class People {
public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";
public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";
public static final String MIME_ITEM = "vnd.example.people";
public static final String MIME_TYPE_SINGLE =MIME_ITEM_PREFIX+"/"+MIME_ITEM;
public static final String MIME_TYPE_MULTIPLE = MIME_DIR_PREFIX+"/"+MIME_ITEM;
public static final String AUTHORITY = "com.example.contentprovider";
public static final String PATH_SINGLE = "people/#";
public static final String PATH_MULTIPLE = "people";
public static final String CONTENT_URI_STRING = "content://"+AUTHORITY+"/"+PATH_SINGLE;
public static final Uri CONTENT_URI =Uri.parse(CONTENT_URI_STRING);
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_AGE = "age";
public static final String KEY_HEIGHT = "height";
}
package com.example.contentprovider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;
public class PeopleProvider extends ContentProvider {
private static final String DB_NAME = "people.db";
private static final String DB_TABLE = "peopleinfo";
private static final int DB_VERSION = 1;
private SQLiteDatabase db;
private DbOpenHelper mDbOpenHelper;
private static final int MULTIPLE_PEOPLE =1;
private static final int SINGLE_PEOPLE =2;
private static final UriMatcher mUriMatcher;
//urimatch的注册
static{
mUriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
mUriMatcher.addURI(People.AUTHORITY, People.PATH_MULTIPLE, MULTIPLE_PEOPLE);
mUriMatcher.addURI(People.AUTHORITY, People.PATH_SINGLE, SINGLE_PEOPLE);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count;
switch (mUriMatcher.match(uri)) {
case MULTIPLE_PEOPLE:
count=db.delete(DB_TABLE, selection, selectionArgs);
break;
case SINGLE_PEOPLE:
String segment=uri.getPathSegments().get(1);//这一句不太明白
count=db.delete(DB_TABLE, People.KEY_ID+"="+segment, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI:" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
switch (mUriMatcher.match(uri)) {
case MULTIPLE_PEOPLE:
return People.MIME_TYPE_MULTIPLE;
case SINGLE_PEOPLE:
return People.MIME_TYPE_SINGLE;
default:
throw new IllegalArgumentException("unkown uri:"+uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long id=db.insert(DB_TABLE, null, values);
if(id>0){
Uri newUri=ContentUris.withAppendedId(People.CONTENT_URI, id);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
throw new SQLException("failed to insert row into:"+uri);
}
@Override
public boolean onCreate() {
Context context=getContext();
mDbOpenHelper=new DbOpenHelper(context, DB_NAME, null, DB_VERSION);
db=mDbOpenHelper.getWritableDatabase();
if(db==null){
return false;
}else{
return true;
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,String sortOrder) {
SQLiteQueryBuilder qb=new SQLiteQueryBuilder();
qb.setTables(DB_TABLE);
switch (mUriMatcher.match(uri)) {
case SINGLE_PEOPLE:
qb.appendWhere(People.KEY_ID+"="+uri.getPathSegments().get(1));
break;
default:
break;
}
Cursor c=qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);//查询返回游标
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count;
switch (mUriMatcher.match(uri)) {
case MULTIPLE_PEOPLE:
count=db.update(DB_TABLE, values, selection, selectionArgs);
break;
case SINGLE_PEOPLE:
String segment = uri.getPathSegments().get(1);//相当于过滤
count=db.update(DB_TABLE, values, People.KEY_ID+"="+segment, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknow URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
/**
* 操作sqlite数据库的类
* @author Administrator
*
*/
private static class DbOpenHelper extends SQLiteOpenHelper{
//创建数据库表的sql语句,省略双引号
// create table peopleinfo ("_id integer primary key autoincrement,name text not null,age integer,height Float);注意这里的空格不要省略
/**
* CREATE TABLE income(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
income_amount TEXT NOT NULL,
income_payer TEXT NOT NULL,
income_date TEXT NOT NULL,
income_category TEXT NOT NULL,
income_payments TEXT NOT NULL
);
*/
//参照上面的不要写错,注意Float包装类型
private static final String DB_CREATE = "CREATE TABLE "+DB_TABLE+" ("+People.KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+People.KEY_NAME+" TEXT NOT NULL,"+People.KEY_AGE+" INTEGER,"+People.KEY_HEIGHT+" Float)";
//private static final String DB_CREATE = "create table user (_id integer PRIMARY KEY AUTOINCREMENT NOT NULL,name varchar,age int)";
public DbOpenHelper(Context context, String name,CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase arg0) {
Log.i("TAG", "建表的sql语句="+DB_CREATE);
arg0.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);
onCreate(db);
}
}
}
上面是provider的代码,注册
android:versionCode="1"
android:versionName="1.0" >
android:targetSdkVersion="19" />
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:exported="true"
android:authorities="com.example.contentprovider" >
下面是访问数据的程序
package com.example.contentproviderdemoactivity;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.LabeledIntent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private EditText nameText;
private EditText ageText;
private EditText heightText;
private EditText idEntity;
private TextView lableView;
private TextView displayView;
private Button btn_add;
private Button btn_queryAll;
private Button btn_clear;
private Button btn_del;
private Button btn_query;
private Button btn_deleteAll;
private Button btn_update;
private ContentResolver resolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
initViews();
resolver=getContentResolver();
}
/**
* 初始化控件
*/
private void initViews() {
nameText=(EditText) findViewById(R.id.name_text);
ageText=(EditText) findViewById(R.id.age_text);
heightText=(EditText) findViewById(R.id.height_text);
idEntity=(EditText) findViewById(R.id.entity_text);
lableView=(TextView) findViewById(R.id.lable_text);
displayView=(TextView) findViewById(R.id.display_text);
btn_add=(Button) findViewById(R.id.btn_add);
btn_clear=(Button) findViewById(R.id.btn_clear);
btn_del=(Button) findViewById(R.id.btn_del);
btn_deleteAll=(Button) findViewById(R.id.btn_deleteAll);
btn_query=(Button) findViewById(R.id.btn_query);
btn_queryAll=(Button) findViewById(R.id.btn_queryall);
btn_update=(Button) findViewById(R.id.btn_update);
btn_add.setOnClickListener(this);
btn_clear.setOnClickListener(this);
btn_del.setOnClickListener(this);
btn_deleteAll.setOnClickListener(this);
btn_query.setOnClickListener(this);
btn_queryAll.setOnClickListener(this);
btn_update.setOnClickListener(this);
}
@Override
public void onClick(View view) {
String msg="";
ContentValues values=new ContentValues();
switch (view.getId()) {
case R.id.btn_add:
values.put(People.KEY_NAME, nameText.getText().toString());
values.put(People.KEY_AGE, ageText.getText().toString());
values.put(People.KEY_HEIGHT, heightText.getText().toString());
Uri newUri=resolver.insert(People.CONTENT_URI, values);
lableView.setText("添加数据成功,URI="+newUri);
break;
case R.id.btn_clear:
break;
case R.id.btn_del:
break;
case R.id.btn_deleteAll:
resolver.delete(People.CONTENT_URI, null, null);
msg="数据全部删除";
displayView.setText(msg);
break;
case R.id.btn_query:
break;
case R.id.btn_queryall:
Cursor c=resolver.query(
People.CONTENT_URI,
new String[]{People.KEY_ID,People.KEY_NAME,People.KEY_AGE,People.KEY_HEIGHT},
null,
null,
null);
if(c==null){
lableView.setText("数据库中没有数据");
return;
}else{
lableView.setText("数据库中有:"+c.getCount()+"条数据。");
if(c.moveToFirst()){
do{
msg+="ID="+c.getString(c.getColumnIndex(People.KEY_ID))+",";
msg+="姓名="+c.getString(c.getColumnIndex(People.KEY_NAME))+",";
msg+="年龄="+c.getString(c.getColumnIndex(People.KEY_AGE))+",";
msg+="身高="+c.getString(c.getColumnIndex(People.KEY_HEIGHT))+",";
}while(c.moveToNext());
}
displayView.setText(msg);
}
break;
case R.id.btn_update:
values = new ContentValues();
values.put(People.KEY_NAME, nameText.getText().toString());
values.put(People.KEY_AGE, Integer.parseInt(ageText.getText().toString()));
values.put(People.KEY_HEIGHT, Float.parseFloat(heightText.getText().toString()));
Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + idEntity.getText().toString());
int result = resolver.update(uri, values, null, null);
msg = "更新ID为" + idEntity.getText().toString() + "的数据" + (result > 0 ? "成功" : "失败");
lableView.setText(msg);
break;
default:
break;
}
}
}
有几个数据库操作没有写,自己写一下。
package com.example.contentproviderdemoactivity;
import android.net.Uri;
public class People {
public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";
public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";
public static final String MIME_ITEM = "vnd.example.people";
public static final String MIME_TYPE_SINGLE =MIME_ITEM_PREFIX+"/"+MIME_ITEM;
public static final String MIME_TYPE_MULTIPLE = MIME_DIR_PREFIX+"/"+MIME_ITEM;
public static final String AUTHORITY = "com.example.contentprovider";
public static final String PATH_SINGLE = "people/#";
public static final String PATH_MULTIPLE = "people";
public static final String CONTENT_URI_STRING = "content://"+AUTHORITY+"/"+PATH_SINGLE;
public static final Uri CONTENT_URI =Uri.parse(CONTENT_URI_STRING);
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_AGE = "age";
public static final String KEY_HEIGHT = "height";
}
上面的数据库语句要格外小心,很难查问题。