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;
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;
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);
}
@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;
}
@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;
}
@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>
您可能感兴趣的文章:Android开发之ContentProvider的使用详解实例讲解Android中ContentProvider组件的使用方法基于Android ContentProvider的总结详解Android中自定义ContentProvider实例深入Understanding Android ContentProvider详解Android编程使用内容提供者方式(ContentProvider)进行存储的方法Android内容提供者ContentProvider用法实例分析Android编程之创建自己的内容提供器实现方法