//Ce qui suit est TestBaidu
MainActivity est la suivante :
package cn.testbaidu; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; /** * Demo描述: * 应用A(TestBaidu)调用另外一个应用(TestContentProvider) * 中的自定义ContentProvider,即: * 1 自定义ContentProvider的使用 * 2 其它应用调用该ContentProvider * * 测试方法: * 1 依次测试ContentProvider的增查删改(注意该顺序) * 2 其它应用查询该ContentProvider的数据 * */ public class MainActivity extends Activity { private Button mAddButton; private Button mDeleteButton; private Button mUpdateButton; private Button mQueryButton; private Button mTypeButton; private ContentResolver mContentResolver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { mContentResolver=this.getContentResolver(); mAddButton=(Button) findViewById(R.id.addButton); mAddButton.setOnClickListener(new ClickListenerImpl()); mDeleteButton=(Button) findViewById(R.id.deleteButton); mDeleteButton.setOnClickListener(new ClickListenerImpl()); mUpdateButton=(Button) findViewById(R.id.updateButton); mUpdateButton.setOnClickListener(new ClickListenerImpl()); mQueryButton=(Button) findViewById(R.id.queryButton); mQueryButton.setOnClickListener(new ClickListenerImpl()); mTypeButton=(Button) findViewById(R.id.typeButton); mTypeButton.setOnClickListener(new ClickListenerImpl()); } private class ClickListenerImpl implements OnClickListener{ @Override public void onClick(View v) { switch (v.getId()) { case R.id.addButton: Person person=null; for (int i = 0; i < 5; i++) { person=new Person("xiaoming"+i, "9527"+i,(8888+i)); testInsert(person); } break; case R.id.deleteButton: testDelete(1); break; case R.id.updateButton: testUpdate(3); break; case R.id.queryButton: //查询表 //queryFromContentProvider(-1); //查询personid=2的数据 testQuery(2); break; case R.id.typeButton: testType(); break; default: break; } } } private void testInsert(Person person) { ContentValues contentValues=new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("phone", person.getPhone()); contentValues.put("salary",person.getSalary()); Uri insertUri=Uri.parse("content://cn.bs.testcontentprovider/person"); Uri returnUri=mContentResolver.insert(insertUri, contentValues); System.out.println("新增数据:returnUri="+returnUri); } private void testDelete(int index){ Uri uri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index)); mContentResolver.delete(uri, null, null); } private void testUpdate(int index){ Uri uri=Uri.parse("content://cn.bs.testcontentprovider/person/"+String.valueOf(index)); ContentValues values=new ContentValues(); values.put("name", "hanmeimei"); values.put("phone", "1234"); values.put("salary", 333); mContentResolver.update(uri, values, null, null); } private void testQuery(int index) { Uri uri=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)); } //对应上面的:查询表 //Cursor cursor= mContentResolver.query(uri, null, null, null, null); //对应上面的:查询personid=2的数据 //注意:因为name是varchar字段的,所以应该写作"name='xiaoming1'" // 若写成"name=xiaoming1"查询时会报错 Cursor cursor= mContentResolver.query(uri, null, "name='xiaoming1'", null, null); while(cursor.moveToNext()){ int personid=cursor.getInt(cursor.getColumnIndex("personid")); String name=cursor.getString(cursor.getColumnIndex("name")); String phone=cursor.getString(cursor.getColumnIndex("phone")); int salary=cursor.getInt(cursor.getColumnIndex("salary")); System.out.println("查询得到:personid=" + personid+",name="+name+",phone="+phone+",salary="+salary); } cursor.close(); } private void testType(){ Uri dirUri=Uri.parse("content://cn.bs.testcontentprovider/person"); String dirType=mContentResolver.getType(dirUri); System.out.println("dirType:"+dirType); Uri itemUri=Uri.parse("content://cn.bs.testcontentprovider/person/3"); String itemType=mContentResolver.getType(itemUri); System.out.println("itemType:"+itemType); } }
La personne est la suivante :
package cn.testbaidu; public class Person { private Integer id; private String name; private String phone; private Integer salary; public Person(String name, String phone,Integer salary) { this.name = name; this.phone = phone; this.salary=salary; } public Person(Integer id, String name, String phone,Integer salary) { this.id = id; this.name = name; this.phone = phone; this.salary=salary; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", phone=" + phone+ ", salary=" + salary + "]"; } }
main.xml est la suivante :
<RelativeLayout xmlns: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>
/ /Ce qui suit est TestContentProvider
MainActivity est la suivante :
package cn.testcontentprovider; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
ContentProviderTest est la suivante :
package cn.testcontentprovider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; /** * 注意事项: * 在AndroidManifest.xml中注册ContentProvider时的属性 * android:exported="true"表示允许其他应用访问. * 这样TestBaidu这个应用才可以访问该处的ContentProvider */ public class ContentProviderTest extends ContentProvider { private DBOpenHelper dbOpenHelper; private UriMatcher URI_MATCHER; private static final int PERSONS = 0; private static final int PERSON = 1; @Override public boolean onCreate() { initUriMatcher(); dbOpenHelper=new DBOpenHelper(getContext()); return true; } //初始化UriMatcher private void initUriMatcher(){ URI_MATCHER=new UriMatcher(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 public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case PERSONS: long rowid=db.insert("person", "name,phone,salary", values); return ContentUris.withAppendedId(uri, rowid); default: throw new IllegalArgumentException("unknown uri"+uri.toString()); } } /** * 更新操作: * 更新操作有两种可能:更新一张表或者更新某条数据 * 在更新某条数据时原理类似于查询某条数据,见下. */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); int updataNum=0; switch (URI_MATCHER.match(uri)) { //更新表 case PERSONS: updataNum=db.update("person", values, selection, selectionArgs); break; //按照id更新某条数据 case PERSON: long id=ContentUris.parseId(uri); String where="personid="+id; if(selection!=null&&!"".equals(selection.trim())){ where=selection+" and "+where; } updataNum=db.update("person", values, where, selectionArgs); break; default: throw new IllegalArgumentException("unknown uri"+uri.toString()); } return updataNum; } /** * 删除操作: * 删除操作有两种可能:删除一张表或者删除某条数据 * 在删除某条数据时原理类似于查询某条数据,见下. */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); int deletedNum=0; switch (URI_MATCHER.match(uri)) { //删除表 case PERSONS: deletedNum=db.delete("person", selection, selectionArgs); break; //按照id删除某条数据 case PERSON: long id=ContentUris.parseId(uri); String where="personid="+id; if(selection!=null&&!"".equals(selection.trim())){ where=selection+" and "+where; } deletedNum=db.delete("person", where, selectionArgs); break; default: throw new IllegalArgumentException("unknown uri"+uri.toString()); } return deletedNum; } /** * 查询操作: * 查询操作有两种可能:查询一张表或者查询某条数据 * 注意事项: * 在查询某条数据时要注意--因为此处是按照personid来查询 * 某条数据,但是同时可能还有其他限制.例如: * 要求personid为2且name为xiaoming1 * 所以在查询时分为两步: * 第一步: * 解析出personid放入where查询条件 * 第二部: * 判断是否有其他限制(如name),若有则将其 * 组拼到where查询条件. * 详细代码见下. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); Cursor cursor; switch (URI_MATCHER.match(uri)) { //查询表 case PERSONS: cursor=db.query("person", projection, selection, selectionArgs, null, null, sortOrder); break; //按照id查询某条数据 case PERSON: //第一步: long id=ContentUris.parseId(uri); String where="personid="+id; //第二步: if(selection!=null&&!"".equals(selection.trim())){ where=selection+" and "+where; } cursor=db.query("person", projection, where, selectionArgs, null, null, sortOrder); break; default: throw new IllegalArgumentException("unknown uri"+uri.toString()); } return cursor; } /** * 返回当前Uri所代表的数据的MIME类型. * 如果该Uri对应的数据可能包含多条记录,那么返回 * 字符串应该以"vnd.android.cursor.dir/"开头 * 如果该Uri对应的数据只包含一条记录,那么返回 * 字符串应该以"vnd.android.cursor.item/"开头 */ @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case PERSONS: return "vnd.android.cursor.dir/persons"; case PERSON: return "vnd.android.cursor.item/person"; default: throw new IllegalArgumentException("unknown uri"+uri.toString()); } } }
DBOpenHelper est la suivante :
package cn.testcontentprovider; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context) { super(context, "contentprovidertest.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table person(personid integer primary key autoincrement,name varchar(20),phone varchar(12),salary Integer(12))"); } //当数据库版本号发生变化时调用该方法 @Override public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { //db.execSQL("ALTER TABLE person ADD phone varchar(12) NULL"); //db.execSQL("ALTER TABLE person ADD salary Integer NULL"); } }
AndroidManifest.xml est le suivant :
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns: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-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android: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> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="cn.testcontentprovider.ContentProviderTest" android:authorities="cn.bs.testcontentprovider" android:exported="true" /> </application> </manifest>
Pour plus d'articles liés aux instances ContentProvider personnalisées dans Android, veuillez prêter attention au site Web PHP chinois !