android的contentProvider

发表于:,更新于:,By Sally
大纲
  1. 1. 先来个常用方法
  2. 2. 在manifest中配置
  3. 3. 定义一个内容提供者,继承contentprovider

先来个常用方法

1
2
UriMatcher(); //用于匹配uri
ContentUri(); //获取和添加uri信息

在manifest中配置

1
2
3
4
<provider
android:name="包名类名全路径"
android:authorities="" > //该标签值随意,保证唯一就行了,一般写全类名

</provider>

定义一个内容提供者,继承contentprovider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class PersonContentProvider extends ContentProvider {

// 类似电话号
private static final String AUTHORITY = "应用程序全包名"; // 与清单文件配置的东西一致

// 操作person表添加操作的uri匹配码
private static final int PERSON_INSERT_CODE = 0;
private static final int PERSON_DELETE_CODE = 1;
private static final int PERSON_UPDATE_CODE = 2;
private static final int PERSON_QUERY_ALL_CODE = 3;

private static UriMatcher uriMatcher;

private MySQLiteOpenHelper openHelper = new MySQLiteOpenHelper();

static {

uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

// 添加一些uri(类似于固话的分机号)
//content://全包名//person/insert 增加操作的uri
uriMatcher.addURI(AUTHORITY, "person/insert", PERSON_INSERT_CODE);
uriMatcher.addURI(AUTHORITY, "person/delete", PERSON_DELETE_CODE);
uriMatcher.addURI(AUTHORITY, "person/update", PERSON_UPDATE_CODE);
uriMatcher.addURI(AUTHORITY, "person/queryAll", PERSON_QUERY_ALL_CODE);
}

@Override
public boolean onCreate() {
return false;
}

@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}

@Nullable
@Override
public String getType(Uri uri) {
return null;
}

@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
switch(uriMatcher.match(uri)) { //匹配uri
case PERSON_INSERT_CODE: //执行insert操作
SQLiteDatabase db = openHelper.getWritableDatabase();

//一些列查询操作
long id = db.insert("pserson", null, values);

//将返回的id追加到uri的末尾
return ContentUris.withAppendedId(uri, id);
break;
}
return null;
}

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

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
r