代码如下:
package com.example.cptest;
//import com.example.cptest.FirstProviderMetaData;
import com.example.cptest.FirstProviderMetaData.UserTableMetaData;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button insert = null;
private Button query = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insert = (Button)findViewById(R.id.insert);
insert.setOnClickListener(new InsertOnClickListener());
query = (Button)findViewById(R.id.query);
query.setOnClickListener(new QueryOnClickListener());
System.out.println(getContentResolver().getType(FirstProviderMetaData.UserTableMetaData.CONTENT_URI));
}
//往子表中插入一条记录
public class InsertOnClickListener implements OnClickListener{
public void onClick(View arg0) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
values.put(FirstProviderMetaData.UserTableMetaData.USER_NAME, "tornadomeet");
//实际上使用的是ContentResolver的insert方法
//该insert中有2个参数,第一个为代表了ContentProvider的Uri,第二个参数为要插入的值。此处的insert函数
//一执行,则自动调用ContentProvider的insert方法。
Uri uri = getContentResolver().insert(FirstProviderMetaData.UserTableMetaData.CONTENT_URI,
values);
System.out.println("uri---" +uri.toString());
}
}
//查询也是采用的ContentResolver中的query方法。
public class QueryOnClickListener implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
Cursor c = getContentResolver().query(FirstProviderMetaData.UserTableMetaData.CONTENT_URI,
null, null, null, null);
while(c.moveToNext())
System.out.println(c.getString(c.getColumnIndex(UserTableMetaData.USER_NAME)));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
DatabaseHelper:
代码如下:
package com.example.cptest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int VERSON = 1;//默认的数据库版本
//继承SQLiteOpenHelper类的类必须有自己的构造函数
//该构造函数4个参数,直接调用父类的构造函数。其中第一个参数为该类本身;第二个参数为数据库的名字;
//第3个参数是用来设置游标对象的,这里一般设置为null;参数四是数据库的版本号。
public DatabaseHelper(Context context, String name, CursorFactory factory, int verson){
super(context, name, factory, verson);
}
//该构造函数有3个参数,因为它把上面函数的第3个参数固定为null了
public DatabaseHelper(Context context, String name, int verson){
this(context, name, null, verson);
}
//该构造函数只有2个参数,在上面函数 的基础山将版本号固定了
public DatabaseHelper(Context context, String name){
this(context, name, VERSON);
}
//该函数在数据库第一次被建立时调用
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
System.out.println("create a database");
//execSQL()为执行参数里面的SQL语句,因此参数中的语句需要符合SQL语法,这里是创建一个表
//arg0.execSQL("create table user1(id int, name varchar(20))");下面的语句格式是与该句类似
// arg0.execSQL("create table" + FirstProviderMetaData.USERS_TABLE_NAME
// + "(" + FirstProviderMetaData.UserTableMetaData._ID
// + " INTEGER PRIMARY KEY AUTOINCREMENT," + //ID类型为自增长的整型
// FirstProviderMetaData.UserTableMetaData.USER_NAME + " varchar(20));"
// );
// arg0.execSQL("create table user1(id int, name varchar(20))");
arg0.execSQL("create table" + FirstProviderMetaData.USERS_TABLE_NAME + "("
+ FirstProviderMetaData.UserTableMetaData._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+FirstProviderMetaData.UserTableMetaData.USER_NAME + " varchar(20))");
System.out.println("create a database ok");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
System.out.println("update a database");
}
}
FirstProviderMetaData.java:
代码如下:
package com.example.cptest;
import android.net.Uri;
import android.provider.BaseColumns;
public class FirstProviderMetaData {
//这里的AUTHORTY为包的全名+ContentProvider子类的全名
public static final String AUTHORTY = "com.example.cptest.FirstContentProvider";
//数据库的名称
public static final String DATABASE_NAME = "FisrtProvider.db";
//数据库的版本号
public static final int DATABASE_VERSION = 1;
//数据库中的表名
public static final String USERS_TABLE_NAME = "users";
//表中的字表
public static final class UserTableMetaData implements BaseColumns{
//子表名
public static final String TABLE_NAME = "users";
//CONTENT_URI为常量Uri; parse是将文本转换成Uri
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORTY + "/users");
//返回ContentProvider中表的数据类型
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.firstprovider.user";
//返回ContentProvider表中item的数据类型
public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.firstprovider.user";
//子表列名
public static final String USER_NAME = "name";
//表中记录的默认排序算法,这里是降序排列
public static final String DEFAULT_SORT_ORDER = "_id desc";
}
}
FirstContentProvider.java:
代码如下:
package com.example.cptest;
import java.util.HashMap;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import com.example.cptest.FirstProviderMetaData.UserTableMetaData;
public class FirstContentProvider extends ContentProvider {
//定义一个UriMatcher类对象,用来匹配Uri的。
public static final UriMatcher uriMatcher;
//组时的ID
public static final int INCOMING_USER_COLLECTION = 1;
//单个时的ID
public static final int INCOMING_USER_SIGNAL = 2;
private DatabaseHelper dh;//定义一个DatabaseHelper对象
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);//UriMatcher.NO_MATCH表示不匹配任何路径的返回码
uriMatcher.addURI(FirstProviderMetaData.AUTHORTY, "users", INCOMING_USER_COLLECTION);
uriMatcher.addURI(FirstProviderMetaData.AUTHORTY, "users/#", INCOMING_USER_SIGNAL);//后面加了#表示为单个
}
public static HashMapString, String userProjectionMap;//新建一个HashMap,后面执行插入操作时有用
static
{
userProjectionMap = new HashMapString, String();
//这里可以直接调用另外一个类的public变量,这里put里面的2个参数一样,
//是因为这里是给数据库表中的列取别名,因此取的是一样的名字
userProjectionMap.put(UserTableMetaData._ID, UserTableMetaData._ID);
userProjectionMap.put(UserTableMetaData.USER_NAME, UserTableMetaData.USER_NAME);
}
//得到ContentProvider的数据类型,返回的参数Uri所代表的数据类型
@Override
public String getType(Uri arg0) {
// TODO Auto-generated method stub
System.out.println("getType");
switch(uriMatcher.match(arg0)){
//matcher满足Uri的前2项(即协议+路径)为第1种情况时,switch语句的值为Uri的第3项,此处为INCOMING_USER_COLLECTION
case INCOMING_USER_COLLECTION:
return UserTableMetaData.CONTENT_TYPE;
case INCOMING_USER_SIGNAL://同上
return UserTableMetaData.CONTENT_TYPE_ITEM;
default:
throw new IllegalArgumentException("Unknown URI" + arg0);//throw是处理异常的,java中的语法
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
System.out.println("delete");
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
System.out.println("update");
return 0;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
System.out.println("insert");
// dh = new DatabaseHelper(getContext(), FirstProviderMetaData.DATABASE_NAME);
SQLiteDatabase db = dh.getWritableDatabase();
long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);
// System.out.println("insert OK");
// System.out.println("" + rowId);
if(rowId 0){
//发出通知给监听器,说明数据已经改变
//ContentUris为工具类
Uri insertedUserUri = ContentUris.withAppendedId(UserTableMetaData.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(insertedUserUri, null);
return insertedUserUri;
}
throw new SQLException("Failed to insert row into" + uri);
}
//回调函数,在ContentProvider创建的时候调用
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
System.out.println("onCreate");
dh = new DatabaseHelper(getContext(), FirstProviderMetaData.DATABASE_NAME);//创建1个DatabaseHelper对象
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
System.out.println("query");
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch(uriMatcher.match(uri)){
case INCOMING_USER_COLLECTION:
qb.setTables(UserTableMetaData.TABLE_NAME);//设置表的名称
qb.setProjectionMap(userProjectionMap);//其中userProjectionMap为上面建立好了的hashmap
break;
case INCOMING_USER_SIGNAL:
qb.setTables(UserTableMetaData.TABLE_NAME);//设置表的名称
qb.setProjectionMap(userProjectionMap);//其中userProjectionMap为上面建立好了的hashmap
//uri.getPathSegments()得到Path部分,即把uri的协议+authory部分去掉,把剩下的部分分段获取,这里取第
//一部分
qb.appendWhere(UserTableMetaData._ID + "=" +uri.getPathSegments().get(1));//设置where条件
break;
}
//排序
String orderBy;
if(TextUtils.isEmpty(sortOrder)){
orderBy = UserTableMetaData.DEFAULT_SORT_ORDER;//传入的排序参数为空的时候采用默认的排序
}
else{
orderBy = sortOrder;//不为空时用指定的排序方法进行排序
}
SQLiteDatabase db = dh.getWritableDatabase();
//采用传入的参数进行查询
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
//发出通知
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
}