服务端:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//初始化数据库信息。 创建表,插入几条数据。
db.execSQL("create table sister(_id integer primary key autoincrement,name text,age integer)");
db.execSQL("insert into sister(name,age) values('小乔',1000)");
db.execSQL("insert into sister(name,age) values('陈圆圆',300)");
db.execSQL("insert into sister(name,age) values('陈汤圆',400)");
db.execSQL("insert into sister(name,age) values('美玲',150)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
import com.example.tz_contentprovider_server.util.MyHelper;
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 MySisterProvider extends ContentProvider {
// Activity子类 onCreate()
private static final String TAG = "TZ";
private static final int ALL = 1;
private static final int SINGLE = 2;
private static final int CONDITION = 3;
private static final int INSERT = 4;
private static final String DB_NAME = "TZ_SISTER.db";
// UriMatcher 可以匹配特定的uri,并且返回一个结果。
private UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private MyHelper helper;
private SQLiteDatabase db;
@Override
public boolean onCreate() {
Log.i(TAG, "执行CP.onCreate()");
initURI();
initDB();
return true;
}
private void initDB() {
// 得到MyHelper
helper = new MyHelper(getContext(), DB_NAME, null, 1);
// 初始化db
db = helper.getWritableDatabase();
}
private void initURI() {
/*
* 将三类特定的uri添加到matcher中。 查询所有 content://com.tz.provider/sisters
*/
matcher.addURI("com.tz.provider", "sisters", ALL);
matcher.addURI("com.tz.provider", "sister/#", SINGLE);
matcher.addURI("com.tz.provider", "sisterWithCondition", CONDITION);
matcher.addURI("com.tz.provider", "insertSister", INSERT);
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
/*
*
* 查询所有 content://com.tz.provider/sisters
*
* 查询特定id content://com.tz.provider/sister/4
*
* 查询特定条件 content://com.tz.provider/sisterWithCondition
*
*
* Log.i(TAG, "执行CP.query() "+uri.toString());
*/
Cursor c = null;
int result = matcher.match(uri);
switch (result) {
case ALL:
c = db.rawQuery("select * from sister", null);
break;
case SINGLE:
// uri---content://com.tz.provider/sister/2
long id = ContentUris.parseId(uri);
c = db.rawQuery("select * from sister where _id=?",
new String[] { id + "" });
break;
case CONDITION:
String sql = "select * from sister";
if (selection != null) {
sql += " where " + selection;
}
// sql- select * from sister where name like %?%
// selectionArgs -- new String[]{ "%圆%" }
c = db.rawQuery(sql, selectionArgs);
break;
case UriMatcher.NO_MATCH:
// 抛出异常
break;
}
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
Log.i(TAG, "执行CP.insert()");
int result=matcher.match(uri);
if(result==INSERT){
// uri-- content://com.tz.provider/insertSister
long id=db.insert("sister", "_id", values);
// newUri -- content://com.tz.provider/insertSister/5
Uri newUri=ContentUris.withAppendedId(uri, id);
return newUri;
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
Log.i(TAG, "执行CP.delete()");
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// Log.i(TAG, "执行CP.update()");
int rowAffected = 0;
int result = matcher.match(uri);
switch (result) {
case ALL:
//更新所有。
rowAffected=db.update(
"sister",
values,
null,
null);
break;
case SINGLE:
long id= ContentUris.parseId(uri);
rowAffected=db.update(
"sister",
values,
"_id=?",
new String[]{id+""});
break;
case CONDITION:
rowAffected=db.update(
"sister",
values,
selection,
selectionArgs);
break;
case UriMatcher.NO_MATCH:
break;
}
return rowAffected;
}
}
客户端:
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private ContentResolver cr;
private static final String CP_PATH="content://com.tz.provider";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//利用上下文可以直接获得 内容获得者ContentResolver 的对象。
cr=getContentResolver();
}
//查询所有
public void queryAll(View v){
Cursor c=cr.query(Uri.parse(CP_PATH+"/sisters"),
null,
null,
null,
null);
handleCursor(c);
}
//查询id为2的妹纸。
public void querySisterById(View v){
//content://com.tz.provider/sister/2
Cursor c=cr.query(Uri.parse("content://com.tz.provider/sister/2"), null, null, null, null);
handleCursor(c);
}
//查询名字里面带圆的妹纸
public void querySistersWithCondition(View v){
//查询特定条件
// content://com.tz.provider/sisterWithCondition
Cursor c=cr.query(Uri.parse("content://com.tz.provider/sisterWithCondition"),
null,
"name like ?",
new String[]{ "%圆%" },
null);
handleCursor(c);
}
private void handleCursor(Cursor c) {
//取出所有数据,并且吐司。
StringBuffer sb=new StringBuffer();
while(c.moveToNext()){
sb.append("_id:"+ c.getInt( c.getColumnIndex("_id") ) +" name:"+ c.getString( c.getColumnIndex("name") ) +" age:"+c.getInt( c.getColumnIndex("age") )+"\n");
}
Toast.makeText(MainActivity.this, sb.toString(), 1).show();
c.close();
}
// 查询
public void query(View v) {
//根据内容获得者以及内容提供者的Authority访问内容提供者的 query()方法
/*
* projection 列名---字符串数组
* selection 条件 "_id = ? or name like ?"
* selectionArgs 条件值 new String[]{"3","%美%"};
* sortOrder 排序的列
*
* uri -- 统一资源标志
* */
// CP_PATH:"content://com.tz.provider"
// content://com.tz.provider/+路径
// content://com.tz.provider/sister
/*
*
* 查询所有
* content://com.tz.provider/sisters
*
* 查询特定id
* content://com.tz.provider/sister/4
*
* 查询特定条件
* content://com.tz.provider/sisterWithCondition
*
* */
cr.query(Uri.parse(CP_PATH+"/sister/4"),
null,
null,
null,
null);
}
//更新所有妹纸年龄为18岁
public void updateAll(View v){
ContentValues values=new ContentValues();
values.put("age", 18);
int rowAffected=cr.update(Uri.parse(CP_PATH+"/sisters"),
values,
null,
null);
Toast.makeText(this, "更新了" + rowAffected + "行", 1).show();
}
//更新id为2的妹纸 年龄为16岁。
public void updateSisterById(View v){
ContentValues values=new ContentValues();
values.put("age", 16);
int rowAffected=cr.update(Uri.parse(CP_PATH+"/sister/2"),
values,
null,
null);
Toast.makeText(this, "更新了" + rowAffected + "行", 1).show();
}
//更新带圆的妹纸的年龄为20岁
public void updateSisterWithCondition(View v){
ContentValues values=new ContentValues();
values.put("age", 20);
int rowAffected=cr.update(Uri.parse(CP_PATH+"/sisterWithCondition"),
values,
"name like ?",
new String[]{"%圆%"});
Toast.makeText(this, "更新了" + rowAffected + "行", 1).show();
}
// 更新
public void update(View v) {
/*
* ContentValues
* key-value
* "age" --- 2000
* */
cr.update(Uri.parse(CP_PATH),
new ContentValues(),
null,
null);
}
// 删除
public void delete(View v) {
cr.delete(Uri.parse(CP_PATH),
null,
null);
}
// 增加
public void insert(View v) {
/*cr.insert(Uri.parse(CP_PATH),
new ContentValues());*/
/*
* 增加一条妹纸记录:
* name:呵呵
* age:30
* */
ContentValues values=new ContentValues();
values.put("name", "呵呵");
values.put("age", 30);
// uri -- content://com.tz.provider/insertSister/5
Uri uri=cr.insert(Uri.parse(CP_PATH+"/insertSister")
, values);
long id=ContentUris.parseId(uri);
Toast.makeText(this, "新增加记录的id:"+id, 1).show();
}
}
整理自教程