zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android中自定义ContentProvider实例

Android实例 自定义 contentprovider
2023-06-13 09:15:02 时间
//以下为TestBaidu
MainActivity如下:
复制代码代码如下:

packagecn.testbaidu;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.app.Activity;
importandroid.content.ContentResolver;
importandroid.content.ContentValues;
importandroid.database.Cursor;
/**
*Demo描述:
*应用A(TestBaidu)调用另外一个应用(TestContentProvider)
*中的自定义ContentProvider,即:
*1自定义ContentProvider的使用
*2其它应用调用该ContentProvider
*
*测试方法:
*1依次测试ContentProvider的增查删改(注意该顺序)
*2其它应用查询该ContentProvider的数据
*
*/
publicclassMainActivityextendsActivity{
privateButtonmAddButton;
privateButtonmDeleteButton;
privateButtonmUpdateButton;
privateButtonmQueryButton;
privateButtonmTypeButton;
privateContentResolvermContentResolver;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
privatevoidinit(){
mContentResolver=this.getContentResolver();

mAddButton=(Button)findViewById(R.id.addButton);
mAddButton.setOnClickListener(newClickListenerImpl());

mDeleteButton=(Button)findViewById(R.id.deleteButton);
mDeleteButton.setOnClickListener(newClickListenerImpl());

mUpdateButton=(Button)findViewById(R.id.updateButton);
mUpdateButton.setOnClickListener(newClickListenerImpl());

mQueryButton=(Button)findViewById(R.id.queryButton);
mQueryButton.setOnClickListener(newClickListenerImpl());

mTypeButton=(Button)findViewById(R.id.typeButton);
mTypeButton.setOnClickListener(newClickListenerImpl());

}
privateclassClickListenerImplimplementsOnClickListener{
@Override
publicvoidonClick(Viewv){
switch(v.getId()){
caseR.id.addButton:
Personperson=null;
for(inti=0;i<5;i++){
person=newPerson("xiaoming"+i,"9527"+i,(8888+i));
testInsert(person);
}
break;
caseR.id.deleteButton:
testDelete(1);
break;
caseR.id.updateButton:
testUpdate(3);
break;
caseR.id.queryButton:
//查询表
//queryFromContentProvider(-1);

//查询personid=2的数据
testQuery(2);
break;
caseR.id.typeButton:
testType();
break;
default:
break;
}

}

}
privatevoidtestInsert(Personperson){
ContentValuescontentValues=newContentValues();
contentValues.put("name",person.getName());
contentValues.put("phone",person.getPhone());
contentValues.put("salary",person.getSalary());
UriinsertUri=Uri.parse("content://cn.bs.testcontentprovider/person");
UrireturnUri=mContentResolver.insert(insertUri,contentValues);
System.out.println("新增数据:returnUri="+returnUri);
}

privatevoidtestDelete(intindex){
Uriuri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index));
mContentResolver.delete(uri,null,null);
}

privatevoidtestUpdate(intindex){
Uriuri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index));
ContentValuesvalues=newContentValues();
values.put("name","hanmeimei");
values.put("phone","1234");
values.put("salary",333);
mContentResolver.update(uri,values,null,null);
}
privatevoidtestQuery(intindex){
Uriuri=null;
if(index<=0){
//查询表
uri=Uri.parse("content://cn.bs.testcontentprovider/person");
}else{
//按照id查询某条数据
uri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index));
}

//对应上面的:查询表
//Cursorcursor=mContentResolver.query(uri,null,null,null,null);

//对应上面的:查询personid=2的数据
//注意:因为name是varchar字段的,所以应该写作"name="xiaoming1""
//若写成"name=xiaoming1"查询时会报错
Cursorcursor=mContentResolver.query(uri,null,"name="xiaoming1"",null,null);

while(cursor.moveToNext()){
intpersonid=cursor.getInt(cursor.getColumnIndex("personid"));
Stringname=cursor.getString(cursor.getColumnIndex("name"));
Stringphone=cursor.getString(cursor.getColumnIndex("phone"));
intsalary=cursor.getInt(cursor.getColumnIndex("salary"));
System.out.println("查询得到:personid="+personid+",name="+name+",phone="+phone+",salary="+salary);
}
cursor.close();
}

privatevoidtestType(){
UridirUri=Uri.parse("content://cn.bs.testcontentprovider/person");
StringdirType=mContentResolver.getType(dirUri);
System.out.println("dirType:"+dirType);

UriitemUri=Uri.parse("content://cn.bs.testcontentprovider/person/3");
StringitemType=mContentResolver.getType(itemUri);
System.out.println("itemType:"+itemType);
}
}

Person如下:
复制代码代码如下:

packagecn.testbaidu;
publicclassPerson{
privateIntegerid;
privateStringname;
privateStringphone;
privateIntegersalary;
publicPerson(Stringname,Stringphone,Integersalary){
this.name=name;
this.phone=phone;
this.salary=salary;
}
publicPerson(Integerid,Stringname,Stringphone,Integersalary){
this.id=id;
this.name=name;
this.phone=phone;
this.salary=salary;
}
publicIntegergetId(){
returnid;
}
publicvoidsetId(Integerid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetPhone(){
returnphone;
}
publicvoidsetPhone(Stringphone){
this.phone=phone;
}
publicIntegergetSalary(){
returnsalary;
}
publicvoidsetSalary(Integersalary){
this.salary=salary;
}
@Override
publicStringtoString(){
return"Person[id="+id+",name="+name+",phone="+phone+",salary="+salary+"]";
}



}

main.xml如下:
复制代码代码如下:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dip"
android:text="增加"
android:textSize="20sp"/>
<Button
android:id="@+id/deleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dip"
android:layout_below="@id/addButton"
android:text="删除"
android:textSize="20sp"/>
<Button
android:id="@+id/updateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dip"
android:layout_below="@id/deleteButton"
android:text="修改"
android:textSize="20sp"/>
<Button
android:id="@+id/queryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dip"
android:layout_below="@id/updateButton"
android:text="查询"
android:textSize="20sp"/>
<Button
android:id="@+id/typeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dip"
android:layout_below="@id/queryButton"
android:text="类型"
android:textSize="20sp"/>
</RelativeLayout>

//以下为TestContentProvider
MainActivity如下:
复制代码代码如下:
packagecn.testcontentprovider;
importandroid.app.Activity;
importandroid.os.Bundle;
publicclassMainActivityextendsActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

ContentProviderTest如下:
复制代码代码如下:
packagecn.testcontentprovider;
importandroid.content.ContentProvider;
importandroid.content.ContentUris;
importandroid.content.ContentValues;
importandroid.content.UriMatcher;
importandroid.database.Cursor;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.net.Uri;
/**
*注意事项:
*在AndroidManifest.xml中注册ContentProvider时的属性
*android:exported="true"表示允许其他应用访问.
*这样TestBaidu这个应用才可以访问该处的ContentProvider
*/
publicclassContentProviderTestextendsContentProvider{
privateDBOpenHelperdbOpenHelper;
privateUriMatcherURI_MATCHER;
privatestaticfinalintPERSONS=0;
privatestaticfinalintPERSON=1;

@Override
publicbooleanonCreate(){
initUriMatcher();
dbOpenHelper=newDBOpenHelper(getContext());
returntrue;
}
//初始化UriMatcher
privatevoidinitUriMatcher(){
URI_MATCHER=newUriMatcher(UriMatcher.NO_MATCH);
//表示返回所有的person,其中PERSONS为该特定Uri的标识码
URI_MATCHER.addURI("cn.bs.testcontentprovider","person",PERSONS);
//表示返回某一个person,其中PERSON为该特定Uri的标识码
URI_MATCHER.addURI("cn.bs.testcontentprovider","person/#",PERSON);
}
/**
*插入操作:
*插入操作只有一种可能:向一张表中插入
*返回结果为新增记录对应的Uri
*方法db.insert()返回结果为新增记录对应的主键值
*/
@Override
publicUriinsert(Uriuri,ContentValuesvalues){
SQLiteDatabasedb=dbOpenHelper.getWritableDatabase();
switch(URI_MATCHER.match(uri)){
casePERSONS:
longrowid=db.insert("person","name,phone,salary",values);
returnContentUris.withAppendedId(uri,rowid);
default:
thrownewIllegalArgumentException("unknownuri"+uri.toString());
}
}

/**
*更新操作:
*更新操作有两种可能:更新一张表或者更新某条数据
*在更新某条数据时原理类似于查询某条数据,见下.
*/
@Override
publicintupdate(Uriuri,ContentValuesvalues,Stringselection,String[]selectionArgs){
SQLiteDatabasedb=dbOpenHelper.getWritableDatabase();
intupdataNum=0;
switch(URI_MATCHER.match(uri)){
//更新表
casePERSONS:
updataNum=db.update("person",values,selection,selectionArgs);
break;
//按照id更新某条数据
casePERSON:
longid=ContentUris.parseId(uri);
Stringwhere="personid="+id;
if(selection!=null&&!"".equals(selection.trim())){
where=selection+"and"+where;
}
updataNum=db.update("person",values,where,selectionArgs);
break;
default:
thrownewIllegalArgumentException("unknownuri"+uri.toString());
}
returnupdataNum;
}

/**
*删除操作:
*删除操作有两种可能:删除一张表或者删除某条数据
*在删除某条数据时原理类似于查询某条数据,见下.
*/
@Override
publicintdelete(Uriuri,Stringselection,String[]selectionArgs){
SQLiteDatabasedb=dbOpenHelper.getWritableDatabase();
intdeletedNum=0;
switch(URI_MATCHER.match(uri)){
//删除表
casePERSONS:
deletedNum=db.delete("person",selection,selectionArgs);
break;
//按照id删除某条数据
casePERSON:
longid=ContentUris.parseId(uri);
Stringwhere="personid="+id;
if(selection!=null&&!"".equals(selection.trim())){
where=selection+"and"+where;
}
deletedNum=db.delete("person",where,selectionArgs);
break;
default:
thrownewIllegalArgumentException("unknownuri"+uri.toString());
}
returndeletedNum;
}
/**
*查询操作:
*查询操作有两种可能:查询一张表或者查询某条数据
*注意事项:
*在查询某条数据时要注意--因为此处是按照personid来查询
*某条数据,但是同时可能还有其他限制.例如:
*要求personid为2且name为xiaoming1
*所以在查询时分为两步:
*第一步:
*解析出personid放入where查询条件
*第二部:
*判断是否有其他限制(如name),若有则将其
*组拼到where查询条件.
*详细代码见下.
*/
@Override
publicCursorquery(Uriuri,String[]projection,Stringselection,String[]selectionArgs,StringsortOrder){
SQLiteDatabasedb=dbOpenHelper.getWritableDatabase();
Cursorcursor;
switch(URI_MATCHER.match(uri)){
//查询表
casePERSONS:
cursor=db.query("person",projection,selection,selectionArgs,null,null,sortOrder);
break;
//按照id查询某条数据
casePERSON:
//第一步:
longid=ContentUris.parseId(uri);
Stringwhere="personid="+id;
//第二步:
if(selection!=null&&!"".equals(selection.trim())){
where=selection+"and"+where;
}
cursor=db.query("person",projection,where,selectionArgs,null,null,sortOrder);
break;
default:
thrownewIllegalArgumentException("unknownuri"+uri.toString());
}
returncursor;
}

/**
*返回当前Uri所代表的数据的MIME类型.
*如果该Uri对应的数据可能包含多条记录,那么返回
*字符串应该以"vnd.android.cursor.dir/"开头
*如果该Uri对应的数据只包含一条记录,那么返回
*字符串应该以"vnd.android.cursor.item/"开头
*/
@Override
publicStringgetType(Uriuri){
switch(URI_MATCHER.match(uri)){
casePERSONS:
return"vnd.android.cursor.dir/persons";
casePERSON:
return"vnd.android.cursor.item/person";
default:
thrownewIllegalArgumentException("unknownuri"+uri.toString());
}
}
}

DBOpenHelper如下:
复制代码代码如下:
packagecn.testcontentprovider;
importandroid.content.Context;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.database.sqlite.SQLiteOpenHelper;
publicclassDBOpenHelperextendsSQLiteOpenHelper{
publicDBOpenHelper(Contextcontext){
super(context,"contentprovidertest.db",null,1);
}
@Override
publicvoidonCreate(SQLiteDatabasedb){
db.execSQL("createtableperson(personidintegerprimarykeyautoincrement,namevarchar(20),phonevarchar(12),salaryInteger(12))");
}
//当数据库版本号发生变化时调用该方法
@Override
publicvoidonUpgrade(SQLiteDatabasedb,intarg1,intarg2){
//db.execSQL("ALTERTABLEpersonADDphonevarchar(12)NULL");
//db.execSQL("ALTERTABLEpersonADDsalaryIntegerNULL");
}
}

AndroidManifest.xml如下:
复制代码代码如下:
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="cn.testcontentprovider"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8"/>
<uses-permissionandroid:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permissionandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="cn.testcontentprovider.MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<provider
android:name="cn.testcontentprovider.ContentProviderTest"
android:authorities="cn.bs.testcontentprovider"
android:exported="true"
/>
</application>
</manifest>