android内容提供者

内容提供者:

必须在清单文件中注册,不需要手动执行,通过内容解决者匹配对应的uri调用对应内容提供者中的增删改查方法,在内容提供者中,事先利用匹配器,匹配一些uri,只有这些uri才能操作该内容提供者。

1、在清单文件中注册

<provider android:name="com.lmj.lianxiren02.MyContentProvider"

android:authorities="com.lmj.lianxiren02.MyContentProvider" 

android:exported="true"/>

Authorities:主机名,也就是访问这个内容提供者的地址。

2、继承ContentPrivoder

Public class MyContentProvider extends ContentProvider 

3、定义匹配器

// 如果没有匹配到就返回-1

static UriMatcher matcher = new UriMatcher(-1);

static String authority = "com.lmj.lianxiren02.MyContentProvider";

 

static int INSERT_CODE = 1;

static int Del_CODE = 2;

static int Up_CODE = 3;

static int Sel_CODE=4;

private MySqliteHelper helper;

// 在匹配器中,定义一些能匹配到的uri

static {

// friend表中插入一条数据的uri

// content://com.lmj.lianxiren02.MyContentProvider/friend

matcher.addURI(authority, "friend", INSERT_CODE);

// 匹配删除操作的uri

matcher.addURI(authority, "friend_delete", Del_CODE);

// 匹配更新的操作的uri

matcher.addURI(authority, "friend_update", Up_CODE);

// 匹配查询的uri

matcher.addURI(authority, "friend_select", Sel_CODE);

 

}

4、覆写oncreate方法,第一次创建内容提供者的时候得到helper对象,利用helper来操作数据库。

@Override

public boolean onCreate() {

// 第一次创建内容提供者的时候,得到helper对象

// 第一个参数上下文,四大组件都可以得到上下文

 

helper = new MySqliteHelper(this.getContext(), "tongxunlu.db", null, 1);

 

return true;

}

5、覆写增删改查数据库的方法

@Override

public Uri insert(Uri uri, ContentValues values) {

 

// 判断uri是否符合规范,如果返回的不是1,说明uri不正确

if (matcher.match(uri) != 1) {

 

throw new IllegalArgumentException("uri不合法" + uri);

 

} else {

SQLiteDatabase sdb = helper.getWritableDatabase();

if (sdb == null) {

throw new IllegalArgumentException("无法插入");

} else {

// 返回插入的这条数据,在数据库中的id

Long id = sdb.insert("friend", "_id", values);

sdb.close();

uri = ContentUris.withAppendedId(uri, id);

// 将这个uri返回给调用者

// com.lmj.lianxiren02.MyContentProvider/friend/id

 

//参数2一般设置为null

//给所有注册了内容观察者的resolver发送一个提醒

this.getContext().getContentResolver().notifyChange(uri, null);

return uri;

 

}

}

 

}

6、调用内容提供者的增删改查方法

内容解决者:

ContentResolver resolver=this.getContentResolver();

resolver.insert(uri, values);

内容解决者调用insert会调用它指定uri对应的内容提供者的insert方法,内容提供者的insert方法执行插入数据库的操作。

 

 

 

<!--EndFragment-->

猜你喜欢

转载自376798041.iteye.com/blog/2187932