您的位置:首页 > 编程语言 > PHP开发

ContentProvider的创建和使用

2016-07-12 23:40 531 查看

(1)首先创建内容提供者,实现暴露数据库程序的功能 定义一个类继承android.content包下的ContentProvider类,ContentProvider是一个抽象类,使用该类时重写            onCreate() getType() query() insert() delete() update()抽 象方法。

        

public class PersonDBProvider extends ContentProvider {
public boolean onCreate() {
return false;
}
public String getType(Uri uri) {
return null;
}
public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
return null;
}
public Uri insert(Uri uri, ContentValues contentValues) {
return null;
}

@Override
public int delete(Uri uri, String s, String[] strings) {
return 0;
}

@Override
public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
return 0;
}
)

 

(2)在清单文件里注册内容提供者 (注意:第二个引号中的内容“包名.自定义名(有一定含义的名字)”,第二个引号中的内容“包名.类名”)

<provider
android:authorities="com.example.hanshu.first.contentResolver"
android:name="com.example.hanshu.first.PersonDBProvider">
</provider>

 

(3)定义匹配器和添加匹配规则

       1. 在PersonDBProvider类中定义一个uri的配置器,用于匹配uri,如果路径不满足条件,返回-1;

       2. 添加匹配规则

           具体代码如下:

          

public class PersonDBProvider extends ContentProvider {
private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
private static final int INSERT=1;
private static final int QUERY=2;
private static final int DELETE=3;
private static final int UPDATE=4;
static {
matcher.addURI("com.example.hanshu.first.contentResolver","insert",INSERT);
matcher.addURI("com.example.hanshu.first.contentResolver","query",QUERY);
matcher.addURI("com.example.hanshu.first.contentResolver","delete",DELETE);
matcher.addURI("com.example.hanshu.first.contentResolver","update",UPDATE);
}
public boolean onCreate() {
return false;
}
public String getType(Uri uri) {
return null;
}
public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) {
return null;
}
public Uri insert(Uri uri, ContentValues contentValues) {
return null;
}

@Override
public int delete(Uri uri, String s, String[] strings) {
return 0;
}

@Override
public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
return 0;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: