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;
import android.util.Log;
public class UserProvider extends ContentProvider{
private DataBaseHelpe 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 {
Log.i("info", "static");
//建立URI和URI_CODE之間的關聯
uriMatcher.addURI(AUTHORITY, "userinfo",1);
uriMatcher.addURI(AUTHORITY, "userinfo/#",2);
}
//該方法在ContentProvider創建後就會被調用,在其他應用第一次訪問它時才會被創建
public boolean onCreate(){
Log.i("info", "onCreate");
dbh=new DataBaseHelpe(getContext());
return false;
}
//該方法用於返回當前Uri所代表數據的MIME類型
public String getType(Uri uri){
Log.i("info", "getType");
switch (uriMatcher.match(uri)){
case 1://操作的數據類型為集合類型,返回值以vnd.android.cursor.dir/開頭
//得到person表的所有數據
return "vnd.android.cursor.dir/userinfo";
case 2://操作的數據類型為非集合類型,返回值以vnd.android.cursor.item/開頭
//得到person表下面,每一條數據
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"
xmlns:tools="http://schemas.android.com/tools"
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
tools:ignore="ExportedContentProvider"
android:name="com.chapt6.UserProvider"
android:authorities="com.chapt6.userprovider"
android:exported="false">
</provider>
</application>
</manifest>
activity_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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.definecontentprovider.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
在DataBaseHelpe 中已經創建了數據庫表,問題點在:UserProvider 沒有在AndroidManifest中注冊