android 內容提供者(ContentProvider)共享SQLite
ContentProvider爲android提供了一種不同應用之間共享數據的可能,次列提供ContentProvider將SQLite的數據庫表 class 共享出來。
1、創建類DBProvider繼承ContentProvider,並且重寫以下方法:
a、onCreate() //創建
b、query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)//查找
c、getType(Uri uri)//返回請求的數據類型
d、insert(Uri uri, ContentValues values)//插入數據
e、delete(Uri uri, String selection, String[] selectionArgs)//刪除數據
f、update(Uri uri, ContentValues values, String selection,
String[] selectionArgs)//更新數據
2、在清單文件中標籤下注冊內容提供者:
<provider
android:name=".DBProvider" //name爲類DBProvider的名字,前面加 “.”
android:authorities="com.example.class_contentporvider_test.DBProvider" >
</provider>//自定義的內容提供者訪問uri
3、創建DBHelper類繼承SQLiteOpenHelper,並重寫如下方法,創建SQLite文件:
public DBHelper(Context context) {
super(context, "test.db", null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "create table class(id integer primary key autoincrement,name varchar(64),number varchar(64))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
關於SQLite的使用詳情,請參照我的上一篇博文:http://blog.csdn.net/q296264785/article/details/53155739
ContentProvider的繼承類DBProvider:
UriMatcher 工具類爲Uri解析提供匹配規則,UriMatcher 的實現類提供addURI方法可以往UriMatcher 添加匹配規則。addURI的第一個參數爲清單文件中我們自定義的android:authorities=”com.example.class_contentporvider_test.DBProvider”;
第二個參數爲訪問數據庫文件的目錄,“*”“#”爲通配符,分別代表“字符”“數字”;第三個爲自定義常量。
private DBHelper helper;
private final static UriMatcher URI_MATCHER = new UriMatcher(
UriMatcher.NO_MATCH);
private final static int one = 1;
private final static int two = 2;
static {
// 添加匹配規則
URI_MATCHER.addURI("com.example.class_contentporvider_test.DBProvider",
"class", two);// 字符
URI_MATCHER.addURI("com.example.class_contentporvider_test.DBProvider",
"class/#", one);// 數字
}
文件目錄表
MainActivity :
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@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;
}
}
DBHelper 類:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static final String SLQ_NAME = "mydb.db";
private static final int VERSION = 1; // ctrl + shift + x 小寫變大寫
public DBHelper(Context context) {
super(context, SLQ_NAME, null, VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "create table person(_pid integer primary key autoincrement,name varchar(64),address varchar(64))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
PersonContentProvider 類
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 PersonContentProvider extends ContentProvider {
private DBHelper helper;
private final static UriMatcher URI_MATCHER = new UriMatcher(
UriMatcher.NO_MATCH);
private final static int PERSONS = 1;// 操作多條記錄
private final static int PERSON = 2;// 操作單行記錄
static {
// url ,路徑 ,
URI_MATCHER.addURI(
// "content://com.example.class_contentprovider.PersonContentProvider/person" 添加
"com.example.class_contentprovider.PersonContentProvider",
"person", PERSONS);
URI_MATCHER.addURI(
"com.example.class_contentprovider.PersonContentProvider",
"person/#", PERSON);
//相當於 "com.example.class_contentprovider.PersonContentProvider" + "person/#" + PERSON 的uil
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
helper = new DBHelper(getContext());
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
Cursor cursor = null;
int flag = URI_MATCHER.match(uri);
SQLiteDatabase database = helper.getReadableDatabase();
switch (flag) {
case PERSON:
long _id = ContentUris.parseId(uri);
String where_value = "_pid = " + _id;
if (selection != null && !selection.equals("")) {
where_value += selection;
}
cursor = database.query("person", projection, where_value,
selectionArgs, null, null, sortOrder);
break;
case PERSONS:
cursor = database.query("person", projection, selection,
selectionArgs, null, null, sortOrder);
break;
}
return cursor;
}
@Override
public String getType(Uri uri) {// 返回處理請求的數據類型
// TODO Auto-generated method stub
// 先解析uri,判斷mime的類型
int flag = URI_MATCHER.match(uri);
switch (flag) {
case PERSON:
return "vnd.android.cursor.item/person";
case PERSONS:
return "vnd.android.cursor.dir/person";
}
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
Uri result = null;
int flag = URI_MATCHER.match(uri);
switch (flag) {
case PERSONS:
SQLiteDatabase database = helper.getReadableDatabase();
long id = database.insert("person", null, values);
result = ContentUris.withAppendedId(uri, id);
break;
}
return result;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
int flag = URI_MATCHER.match(uri);
SQLiteDatabase database = helper.getWritableDatabase();
int count = 0;
switch (flag) {
case PERSON:
long _id = ContentUris.parseId(uri);
String where_value = "_pid = " + _id;
if (selection != null && !selection.equals("")) {
where_value += selection;
}
count = database.delete("person", where_value, selectionArgs);
break;
case PERSONS:
count = database.delete("person", selection, selectionArgs);
break;
}
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
int flag = URI_MATCHER.match(uri);
int count = 0;
SQLiteDatabase database = helper.getWritableDatabase();
switch (flag) {
case PERSON:
long _id = ContentUris.parseId(uri);
String where_value = "_pid = " + _id;
if (selection != null && !selection.equals("")) {
where_value += selection;
}
count = database.update("person", values, where_value,
selectionArgs);
break;
}
return count;
}
}
單元測試類:
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
public class MyTest extends AndroidTestCase {
public void add() {// 添加
ContentResolver contentResolver = getContext().getContentResolver();
ContentValues values = new ContentValues();
values.put("name", "源信");
values.put("address", "高新區");
Uri uri = Uri
.parse("content://com.example.class_contentprovider.PersonContentProvider/person");
contentResolver.insert(uri, values);
}
public void del() {// 刪除
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.class_contentprovider.PersonContentProvider/person");
Uri new_uri = ContentUris.withAppendedId(uri, 1);
contentResolver.delete(new_uri, null, null);
}
public void query() {// 查找
ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = Uri
.parse("content://com.example.class_contentprovider.PersonContentProvider/person");
Uri new_uri = ContentUris.withAppendedId(uri, 2);
Cursor cursor = contentResolver.query(new_uri, null, null, null, null);
while (cursor.moveToNext()) {
String str = cursor.getString(cursor.getColumnIndex("name"));
System.out.println("---query->>" + str);
}
}
}