DataBaseHelpe.java
package com.example.definecontentprovider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelpe extends SQLiteOpenHelper{
public static final String DB_NAME="userdb.db";
public static final String TABLENAME="userinfo";
public static final int DB_VERSION=1;
public static final String CREATETABLE="create table"+TABLENAME+"(_id integer primary key,username text,userpassword text);";
public DataBaseHelpe(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATETABLE);
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
Log.i("Database update......","Update database from"+oldVersion+"to"+newVersion);
db.execSQL("drop table if it exists"+TABLENAME);
onCreate(db);
}
}
MainActivity.java
package com.example.definecontentprovider;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver cr=getContentResolver();
//增加记录
ContentValues values=new ContentValues();
values.put("username","admin");
values.put("userpassword","123456");
cr.insert(UserProvider.CONTENT_URI, values);
values.clear();
values.put("username","zhangsan");
values.put("userpassword","666666");
cr.insert(UserProvider.CONTENT_URI, values);
//查询所有记录
Cursor cursor=cr.query(UserProvider.CONTENT_URI, null, null, null, null);
Log.i("after inserted","-------------------------");
while(cursor.moveToNext()){
Log.i("after inserted","id:"+cursor.getString(0)+"username:"+cursor.getString(1)+"userpassword:"+cursor.getString(2));
}
cursor.close();
//修改记录
values.clear();
values.put("username","lisi");
//构建的Uri为:"content://com.chapt6.userprovider/userinfo/2"
Uri uri=ContentUris.withAppendedId(UserProvider.CONTENT_URI,2);
//修改id为2的记录
cr.update(uri, values, null, null);
//查询id为2的记录
cursor=cr.query(uri, null, null, null, null);
Log.i("after updated","-------------------------");
while(cursor.moveToNext()){
Log.i("after updated","id:"+cursor.getString(0)+"username:"+cursor.getString(1)+"userpassword:"+cursor.getString(2));
}
cursor.close();
//删除id为2的记录
cr.delete(uri, null, null);
//查询记录
cursor=cr.query(UserProvider.CONTENT_URI, null, null, null, null);
Log.i("after deleted","-------------------------");
while(cursor.moveToNext()){
Log.i("after deleted","id:"+cursor.getString(0)+"username:"+cursor.getString(1)+"userpassword:"+cursor.getString(2));
}
cursor.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
UserProvider.java
package com.example.definecontentprovider;
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 UserProvider extends ContentProvider{
private DataBaseHelper dbh=null;
//发布Content Provider的Uri地址
private static final String AUTHORITY="com.chapt6.userprovider";
public static final Uri CONTENT_URI=Uri.parse("content://com.chapt6.userprovider/userinfo");
//注册需要匹配的Uri
private static UriMatcher uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, "userinfo",1);
uriMatcher.addURI(AUTHORITY, "userinfo/#",2);
}
//该方法在ContentProvider创建后就会被调用,在其他应用第一次访问它时才会被创建
public boolean onCreate(){
dbh=new DataBaseHelper(getContext());
return false;
}
//该方法用于返回当前Uri所代表数据的MIME类型
public String getType(Uri uri){
switch (uriMatcher.match(uri)){
case 1:
return "vnd.android.cursor.dir/userinfo";
case 2:
return "vnd.android.cursor.item/userinfo";
}
return null;
}
//该方法用于供外部应用从ContentProvider删除数据
public int delete(Uri uri,String selection,String[] selectionArgs){
SQLiteDatabase db=dbh.getWritableDatabase();
int num=0;
switch(uriMatcher.match(uri)){
case 1:
num=db.delete("userinfo",selection,selectionArgs);
break;
case 2:
long id=ContentUris.parseId(uri);
if(selection==null){
selection="_id="+id;
}
else{
selection="_id="+id+" and ("+selection+")";
}
num=db.delete("userinfo",selection,selectionArgs);
break;
default:
break;
}
getContext().getContentResolver().notifyChange(uri, null);
return num;
}
//该方法用于供外部应用往ContentProvider添加数据
public Uri insert(Uri uri,ContentValues values){
SQLiteDatabase db=dbh.getWritableDatabase();
long id=db.insert("userinfo", null, values);
if(id>-1)//插入数据成功
{//构建新插入行的Uri
Uri insertUri=ContentUris.withAppendedId(CONTENT_URI, id);
//通知所有的观察者,数据集已经改变
getContext().getContentResolver().notifyChange(insertUri, null);
return insertUri;
}
return null;
}
//该方法用于供外部应用从ContentProvider中获取数据
public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder){
SQLiteDatabase db=dbh.getReadableDatabase();
Cursor cursor=null;
switch(uriMatcher.match(uri)){
case 1:
cursor=db.query("userinfo",//表名
null,//列的数组,null代表所有列
selection,//where条件
selectionArgs,//where条件的参数值的数组
null,//分组
null,//having
sortOrder);//排序规则
break;
case 2:
long id=ContentUris.parseId(uri);
if(selection==null){
selection="_id="+id;
}
else{
selection="_id="+id+" and ("+selection+")";
}
cursor=db.query("userinfo",
null,
selection,
selectionArgs,
null,
null,
sortOrder);
break;
default:
break;
}
return cursor;
}
//该方法用于供外部应用更新ContentProvider中的数据
public int update(Uri uri,ContentValues values,String selection,String[] selectionArgs){
SQLiteDatabase db=dbh.getWritableDatabase();
int num=0;
switch(uriMatcher.match(uri)){
case 1:
num=db.update("userinfo",values,selection,selectionArgs);
break;
case 2:
long id=ContentUris.parseId(uri);
//在selection上增加条件_id=id
if(selection==null){
selection="_id="+id;
}
else{
selection="_id="+id+" and ("+selection+")";
}
num=db.update("userinfo",values,selection,selectionArgs);
break;
default:
break;
}
getContext().getContentResolver().notifyChange(uri, null);
return num;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.definecontentprovider"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".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=".UserProvider"
android:authorities=".userprovider"
android:exported="true">
</provider>
</application>
</manifest>