Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中自定義ContentProvider實例

Android中自定義ContentProvider實例

編輯:關於Android編程

//以下為TestBaidu
MainActivity如下:
復制代碼 代碼如下:
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);
}
}

Person如下:
復制代碼 代碼如下:
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如下:
復制代碼 代碼如下:
<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>

//以下為TestContentProvider
MainActivity如下:
復制代碼 代碼如下:
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如下:
復制代碼 代碼如下:
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如下:
復制代碼 代碼如下:
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如下:
復制代碼 代碼如下:
<?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>
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved