Android的ContentProvider

  • 内容
  • 评论
  • 相关

 一、概述

 ContentProvider(数据提供者)是应用程序之间共享数据的一种接口机制,是一种更为高级的数据共享方法。

  • ContentProvider可以指定需要共享的数据,而其他应用程序则可以在不知道数据来源、路径的情况下,对共享数据进行增删改查等操作。
  • 在Android系统中,许多Android系统内置的数据也是通过ContentProvider提供给用户使用,例如通讯录、音视频文件和图像文件等

 二、使用关系

 三、类关系

  • CPP与CPN是一对Binder通信的C/S两端;
  • ACR(ApplicationContentResolver)继承于ContentResolver, 位于ContextImpl的内部类. ACR的实现往往是通过调用其成员变量mMainThread(数据类型为ActivityThread)来完成;

四、ContentProvider中的URI

 
因为Uri代表了要操作的数据,所以我们经常需要解析Uri,并从Uri中获取数据。Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher和ContentUris 。

4.1.  UriMatcher

UriMatcher 类主要用于匹配Uri.
使用方法
1.初始化
1
mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
2.注册需要的Uri
1
2
3
4
sAuthority = getContext().getPackageName() + "." + AoaoyiContentProvider.class.getSimpleName();
mUriMatcher.addURI(sAuthority, DBData.TABLE_USER, 1);
mUriMatcher.addURI(sAuthority, DBData.TABLE_USER + "/raw", 2);
mUriMatcher.addURI(sAuthority, DBData.TABLE_SP, 3);
3.与已经注册的Uri进行匹配(match方法匹配后会返回一个匹配码Code,即在使用注册方法addURI时传入的第三个参数。)
switch (mUriMatcher.match(uri)) {
    case 1:
        cursor = db.query(DBData.TABLE_USER, projection, selection, selectionArgs, null, null, sortOrder, null);
        break;
    case 2:
        cursor = db.rawQuery(selection, selectionArgs);
        break;
    case 3:
        cursor = db.query(DBData.TABLE_SP, projection, selection, selectionArgs, null, null, sortOrder, null);
        break;
}

4.2.  ContentUris

ContentUris 类用于获取Uri路径后面的ID部分
使用方法:
1. 为路径加上ID: withAppendedId(uri, id)
1
ContentUris.withAppendedId(uri, id);ContentUris.parseId(uri)
1. 从路径中获取ID: parseId(uri)
1
ContentUris.parseId(uri)

五、具体实现

我下面实现一个APP内跨进程访问数据的例子,目的是利用ContentProvider确保跨进程操作数据安全:

1. 需要在AndroidManifest.xml使用<provider>对该ContentProvider进行配置,为了能让其他应用找到该ContentProvider ,ContentProvider采用了authorities(主机名/域名)对它进行唯一标识,你可以把ContentProvider看作是一个网站(想想,网站也是提供数据者),authorities 就是他的域名:

1
2
3
4
5
<provider
   android:name="com.aoaoyi.provider.AoaoyiContentProvider"
   android:authorities="{AppPackageName}.AoaoyiContentProvider"
   android:enabled="true"
   android:exported="true" />

2.创建AoaoyiContentProvider.java

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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
public class AoaoyiContentProvider extends ContentProvider{
    private static final String TAG = AoaoyiContentProvider.class.getSimpleName();
 
    private DBHelper mDBHelper;
    private UriMatcher mUriMatcher;
    private ContentResolver mResolver;
 
    public static String sAuthority;
 
    @Override
    public boolean onCreate() {
        mDBHelper = DBHelper.getInstance(getContext());
        mResolver = getContext().getContentResolver();
        sAuthority = getContext().getPackageName() + "." + AoaoyiContentProvider.class.getSimpleName();
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        mUriMatcher.addURI(sAuthority, DBData.TABLE_USER, 1);
        mUriMatcher.addURI(sAuthority, DBData.TABLE_USER + "/raw", 2);
        mUriMatcher.addURI(sAuthority, DBData.TABLE_SP, 3);
        return true;
    }
 
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Cursor cursor = null;
        try {
            SQLiteDatabase db = mDBHelper.getWritableDatabase();
 
            switch (mUriMatcher.match(uri)) {
                case 1:
                    cursor = db.query(DBData.TABLE_USER, projection, selection, selectionArgs, null, null, sortOrder, null);
                    break;
                case 2:
                    cursor = db.rawQuery(selection, selectionArgs);
                    break;
                case 3:
                    cursor = db.query(DBData.TABLE_SP, projection, selection, selectionArgs, null, null, sortOrder, null);
                    break;
            }
        }
        catch (Exception e) {
            Log.i(TAG, "query:Exception:" + e.toString());
        } catch (Error e) {
            Log.i(TAG, "query:Error:" + e.toString());
        }
 
        return cursor;
    }
 
 
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        String result = null;
        switch (mUriMatcher.match(uri)) {
            case 1:
            case 2:
                result = "vnd.android.cursor.dir/vnd." + AoaoyiContentProvider.class.getName() + "." + DBData.TABLE_USER;
                break;
            case 3:
                result = "vnd.android.cursor.item/vnd." + AoaoyiContentProvider.class.getName() + "." + DBData.TABLE_SP;
                break;
        }
 
        return result;
    }
 
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        Uri result = null;
        long id = -1;
        try {
            SQLiteDatabase db = mDBHelper.getWritableDatabase();
            switch (mUriMatcher.match(uri)) {
                case 1:
                case 2:
                    id = db.insert(DBData.TABLE_USER, null, values);
                    break;
                case 3:
                    id = db.insert(DBData.TABLE_SP, null, values);
                    break;
            }
            if(id < 0) {
                result = uri;
            } else {
                result = ContentUris.withAppendedId(uri, id);
                mResolver.notifyChange(result, null);
            }
            Log.d(TAG, "insert:" + id);
        } catch (Exception e) {
            Log.i(TAG, "insert:Exception:" + e.toString());
        } catch (Error e) {
            Log.i(TAG, "insert:Error:" + e.toString());
        }
 
        return result;
    }
 
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        int result = 0;
        try {
            SQLiteDatabase db = mDBHelper.getWritableDatabase();
            switch (mUriMatcher.match(uri)) {
                case 1:
                    result = db.delete(DBData.TABLE_USER, selection, selectionArgs);
                    break;
                case 2:
                    db.execSQL(selection);
                    break;
                case 3:
                    result = db.delete(DBData.TABLE_SP, selection, selectionArgs);
                    break;
            }
            Log.d(TAG, "delete:" + result);
        } catch (Exception e) {
            result = 0;
            Log.i(TAG, "delete:Exception:" + e.toString());
        } catch (Error e) {
            result = 0;
            Log.i(TAG, "delete:Error:" + e.toString());
        }
 
        return result;
    }
 
    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        int result = 0;
        try {
            SQLiteDatabase db = mDBHelper.getWritableDatabase();
            switch (mUriMatcher.match(uri)) {
                case 1:
                    result = db.update(DBData.TABLE_USER, values, selection, selectionArgs);
                    break;
                case 2:
                    db.execSQL(selection);
                    break;
                case 3:
                    result = db.update(DBData.TABLE_SP, values, selection, selectionArgs);
                    break;
            }
 
            if(result > 0)
                mResolver.notifyChange(uri, null);
            Log.d(TAG, "update:" + result);
        } catch (Exception e) {
            result = 0;
            Log.i(TAG, "update:Exception:" + e.toString());
        } catch (Error e) {
            result = 0;
            Log.i(TAG, "update:Error:" + e.toString());
        }
 
        return result;
    }
}

3.其中用到的DBData.java

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
72
73
74
75
public class DBData {
    /* 数据库 */
    /** SDK 本地数据库名 */
    public static final String DB_NAME = "aoaoyi_db";
    /** SDK 本地数据库的版本号,用于数据升级 */
    public static final int DB_VERSION = 1;
 
    /* ====== SP BEGIN =======*/
    /** SharePreference 表名*/
    public static final String TABLE_SP = "sp";
    /** 自增字段 */
    public static final String SP_AUTO_ID = "_id";
    /** Key */
    public static final String SP_KEY = "key";
    /** Value */
    public static final String SP_VALUE = "value";
    /** CreateTime */
    public static final String SP_CREATE_TIME = "create_time";
 
    /** 创建SP表 */
    public static final String SQL_CREATE_SP = "CREATE TABLE IF NOT EXISTS "
            + TABLE_SP + "("
            + SP_AUTO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + SP_KEY + " VARCHAR,"
            + SP_VALUE + " VARCHAR,"
            + SP_CREATE_TIME + " INTEGER DEFAULT (strftime('%s','now')*1000))";
 
    /** 添加表索引 */
    public static final String SQL_CREATE_SP_INDEX = "CREATE INDEX IF NOT EXISTS "
            + " sp_key_index "
            + " on "
            + TABLE_SP
            + " ( "
            + SP_KEY
            + " ) ";
 
    /* ====== SP END =======*/
 
    /* ====== USER BEGIN =======*/
    public static final String TABLE_USER = "user";
    public static final String USER_AUTO_ID = "_id";
    public static final String USER_ID = "id";
    public static final String USER_NICK_NAME = "nick_name";
    public static final String USER_PROFILE_PIC_URL = "profile_pic_url";
    public static final String USER_PHONE_NUM = "phone_num";
    public static final String USER_EMAIL = "email";
    public static final String USER_ADDRESS = "address";
    public static final String USER_CREATE_TIME = "user_create_time";
 
    /** create table */
    public static final String SQL_CREATE_USER = "CREATE TABLE IF NOT EXISTS "
            + TABLE_USER + "("
            + USER_AUTO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + USER_ID + " INTEGER,"
            + USER_NICK_NAME + " VARCHAR,"
            + USER_PROFILE_PIC_URL + " VARCHAR,"
            + USER_PHONE_NUM + " VARCHAR,"
            + USER_EMAIL + " VARCHAR,"
            + USER_ADDRESS + " TEXT,"
            + USER_CREATE_TIME + " INTEGER DEFAULT (strftime('%s','now')*1000))";
 
    /** 添加表索引 */
    public static final String SQL_CREATE_USER_INDEX = "CREATE INDEX IF NOT EXISTS "
            + " user_phone_index "
            + " on "
            + TABLE_USER
            + " ( "
            + USER_ID
            + ", "
            + USER_PHONE_NUM
            + " ) ";
 
    /* ====== USER END =======*/
 
}

4.其中用到的DBHelper.java

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
72
73
public class DBHelper extends SQLiteOpenHelper {
    /** TAG */
    private static final String TAG = DBHelper.class.getSimpleName();
    /** DBHelper */
    private volatile static DBHelper mDBHelper = null;
 
    /**
     * DBHelper 单例模式调用
     *
     * @param pContext Context
     *
     * @return SQLiteOpenHelper
     */
    public static DBHelper getInstance(Context pContext) {
        if (mDBHelper == null) {
            synchronized(DBHelper.class){
                if (mDBHelper == null) {
                    mDBHelper = new DBHelper(pContext.getApplicationContext());
                }
            }
        }
        return mDBHelper;
    }
 
 
    private DBHelper(Context pContext) {
        super(pContext, DBData.DB_NAME, null, DBData.DB_VERSION);
    }
 
    @Override
    public void onCreate(SQLiteDatabase pDB) {
        //User
        pDB.execSQL(DBData.SQL_CREATE_USER);
        pDB.execSQL(DBData.SQL_CREATE_USER_INDEX);
        //SP
        pDB.execSQL(DBData.SQL_CREATE_SP);
        pDB.execSQL(DBData.SQL_CREATE_SP_INDEX);
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase pDB, int pOldVersion, int pNewVersion) {
        for (int i = pOldVersion; i < pNewVersion; i++) {
            List<String> _UpgradeSQLList = getUpgradeSQL(i + 1);
            for (String _UpgradeSQL : _UpgradeSQLList) {
                try {
                    pDB.execSQL(_UpgradeSQL);
                } catch (Exception e) {
                    Log.e(getClass().getSimpleName(), "catch SQLException in onUpgrade() method", e);
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 各个版本更新数据的SQL语句
     *
     * @param pVersion 版本号
     *
     * @return 各个版本需要更新的SQL语句的集合
     */
    private List<String> getUpgradeSQL(int pVersion) {
        //数据库所做的升级SQL语句
        List<String> _UpgradeSQLList = new ArrayList<>();
        switch (pVersion) {
            case 2:
 
                break;
            case 3:
                break;
        }
        return _UpgradeSQLList;
    }
}

5.其中用到的SPDao.java

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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
public class SPDao {
    /** TAG */
    private static final String TAG = SPDao.class.getSimpleName();
    /** */
    private final byte[] sLock = new byte[0];
    private Context mContext;
    /** Authority */
    private static String mAuthority;
    /** 访问该ContentProvider的URI */
    private static Uri mUri;
 
    public SPDao(Context pContext){
        mContext = pContext.getApplicationContext();
        mAuthority = pContext.getPackageName() + "." + AoaoyiContentProvider.class.getSimpleName();
        mUri = Uri.parse("content://" + mAuthority + "/" + DBData.TABLE_SP);
    }
 
    /**
     * 插入Key和Value(存在进行更新,不存在进行插入)
     *
     * @param pKey key
     * @param pValue value
     * @return
     */
    public long insertKeyValue(final String pKey, final String pValue) {
        synchronized (sLock) {
            int result;
            try {
                if(!TextUtils.isEmpty(pKey) && !TextUtils.isEmpty(pValue)){
                    ContentValues cv = new ContentValues();
                    if (!isExistKey(pKey)){
                        //不存在插入
                        cv.put(DBData.SP_KEY, pKey);
                        cv.put(DBData.SP_VALUE, pValue);
                        Uri uri = mContext.getContentResolver().insert(mUri, cv);
                        if(ContentUris.parseId(uri) > 0){
                            Log.d(TAG, "Key:" + pKey + " value set to :" + pValue);
                            result = 1;
                        }else {
                            result = 0;
                            Log.d(TAG, "Key:" + pKey + " value set fail ");
                        }
                    }else {
                        //存在进行更新
                        cv.put(DBData.SP_VALUE, pValue);
                        String whereClause = DBData.SP_KEY + " = ? ";
                        String[] whereArgs = new String[] { pKey };
                        result = mContext.getContentResolver().update(mUri, cv, whereClause, whereArgs);
                        if (result > 0){
                            Log.d(TAG, "Key:" + pKey + " value update to :" + pValue);
                        }else {
                            Log.d(TAG, "Key:" + pKey + " value update fail ");
                        }
                    }
                }else {
                    result = 0;
                    Log.d(TAG, "Key or value is null ");
                }
            } catch (Exception e) {
                result = 0;
                Log.i(TAG, "insert:Exception:" + e.toString());
            } catch (Error e) {
                result = 0;
                Log.i(TAG, "insert:Error:" + e.toString());
            }
            return result;
        }
    }
 
    /**
     * 移除KeyValue
     *
     * @param pKey
     * @return 受影响的条数
     */
    public long removeKeyValue(final String pKey){
        synchronized(sLock) {
            long result;
            try {
                String whereClause = DBData.SP_KEY + " = ? ";
                String[] whereArgs = new String[] { pKey };
                result = mContext.getContentResolver().delete(mUri, whereClause, whereArgs);
                if (result > 0){
                    Log.d(TAG, "delete key:" + pKey + " success ");
                }else {
                    Log.d(TAG, "delete key:" + pKey + " fail ");
                }
            } catch (Exception e) {
                result = 0;
                Log.i(TAG, "remove:Exception:" + e.toString());
            } catch (Error e) {
                result = 0;
                Log.i(TAG, "remove:Error:" + e.toString());
            }
            return result;
        }
    }
 
    /**
     * 获取Value
     *
     * @param pKey Key
     * @return
     */
    public String getValueByKey(final String pKey){
        synchronized (sLock) {
            String value = "";
            try {
                String selection =  DBData.SP_KEY + " = ? ";
                String[] whereArgs = new String[] { pKey };
                String orderBy =  DBData.SP_AUTO_ID + " DESC ";
                Cursor cursor = mContext.getContentResolver().query(mUri, null, selection, whereArgs, orderBy);
                if (cursor != null && cursor.getCount() > 0) {
                    if (cursor.moveToFirst()){
                        value = cursor.getString(cursor.getColumnIndex(DBData.SP_VALUE));
                        Log.d(TAG, "Key:" + pKey + " value:" + value);
                    }
                }
                cursor.close();
            } catch (Exception e) {
                Log.i(TAG, "query:Exception:" + e.toString());
            } catch (Error e) {
                Log.i(TAG, "query:Error:" + e.toString());
            }
            return value;
        }
    }
 
    /**
     * 是否存在Key
     *
     * @param pKey key
     * @return true:存在;false:不存在;
     */
    private boolean isExistKey(final String pKey){
        synchronized (sLock) {
            Boolean result;
            try {
                String selection =  DBData.SP_KEY + " = ? ";
                String[] whereArgs = new String[] { pKey };
                Cursor cursor = mContext.getContentResolver().query(mUri, null, selection, whereArgs, null);
                result = cursor.getCount() > 0 ? true : false;
                cursor.close();
            } catch (Exception e) {
                result = false;
                Log.i(TAG, "exist:Exception:" + e.toString());
            } catch (Error e) {
                result = false;
                Log.i(TAG, "exist:Error:" + e.toString());
            }
            return result;
        }
    }
}

6.其中用到的UserInfoDao.java

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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
public class UserInfoDao {
    private static final String TAG = UserInfoDao.class.getSimpleName();
    private final byte[] sLock = new byte[0];
    private Context mContext;
    /** Authority */
    private static String mAuthority;
    /** Uri */
    private static Uri mUri;
    /** Raw Uri */
    private static Uri mRawUri;
 
    public UserInfoDao(Context pContext){
        mContext = pContext.getApplicationContext();
        mAuthority = pContext.getPackageName() + "." + AoaoyiContentProvider.class.getSimpleName();
        mUri = Uri.parse("content://" + mAuthority + "/" + DBData.TABLE_USER);
        mRawUri = Uri.parse("content://" + mAuthority + "/" + DBData.TABLE_USER + "/raw");
    }
 
    public long insertList(List<UserInfo> userInfoList){
        synchronized (sLock) {
            int insertResult = 0;
            if (userInfoList == null){
                return insertResult;
            }
            ContentValues cv = new ContentValues();
            try{
                for (UserInfo userInfo : userInfoList){
                    if(isExist(userInfo.getUserId())){
                        //存在更新
                        cv = toContentValues(cv, userInfo);
                        String contentValues = DBData.USER_ID + " = ? ";
                        String[] whereArgs = new String[] { String.valueOf(userInfo.getUserId()) };
                        insertResult = mContext.getContentResolver().update(mUri, cv, contentValues, whereArgs);
                    }else {
                        //不存在,进行插入
                        cv = toContentValues(cv, userInfo);
                        Uri uri = mContext.getContentResolver().insert(mUri, cv);
                        if(ContentUris.parseId(uri) > 0){
                            insertResult ++;
                            Log.i(TAG, "UserId::" + userInfo.getUserId());
                        }
                    }
                }
            } catch (Exception e){
                Log.i(TAG, "insert:Exception:" + e.toString());
            } catch (Error e) {
                Log.i(TAG, "insert:Error:" + e.toString());
            }
            return insertResult;
        }
    }
 
    public long updateUserInfo(final UserInfo pUserInfo){
        synchronized(sLock) {
            long updateResult = 0;
            if (pUserInfo != null){
                try{
                    ContentValues cv = new ContentValues();
                    if (isExist(pUserInfo.getUserId())){
                        //存在
                        cv = toContentValues(cv, pUserInfo);
                        String contentValues = DBData.USER_ID + " = ? ";
                        String[] whereArgs = new String[] { String.valueOf(pUserInfo.getUserId()) };
                        updateResult = mContext.getContentResolver().update(mUri, cv, contentValues, whereArgs);
                    }
                } catch (Exception e){
                    Log.i(TAG, "update:Error:" + e.toString());
                } catch (Error e) {
                    Log.i(TAG, "update:Error:" + e.toString());
                }
            }
            return updateResult;
        }
    }
 
    public boolean isExist(final int pUserId){
        synchronized (sLock) {
            Boolean result;
            try {
                String[] columns = new String[] { DBData.USER_ID };
                String selection = DBData.USER_ID + " = ? ";
                String[] whereArgs = new String[] { String.valueOf(pUserId)};
                Cursor cursor = mContext.getContentResolver().query(mUri, columns, selection, whereArgs, null);
                result = cursor.getCount() > 0 ? true : false;
                cursor.close();
            } catch (Exception e) {
                result = false;
                Log.i(TAG, "exist:Exception:" + e.toString());
            } catch (Error e) {
                result = false;
                Log.i(TAG, "exist:Error:" + e.toString());
            }
            return result;
        }
    }
 
    public List<UserInfo> getUserInfoList() {
        synchronized (sLock) {
            List<UserInfo> userInfoList = null;
            try{
                String orderBy = DBData.USER_CREATE_TIME + " DESC " ;
                Cursor cursor = mContext.getContentResolver().query(mUri, null, null, null, orderBy);
                if (cursor != null) {
                    userInfoList = new ArrayList<>(cursor.getCount());
                    for(cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()){
                        UserInfo userInfo = toUserInfo(cursor);
                        userInfoList.add(userInfo);
                    }
                    cursor.close();
                }
            } catch (Exception e) {
                Log.i(TAG, "query:Exception:" + e.toString());
            } catch (Error e) {
                Log.i(TAG, "query:Error:" + e.toString());
            }
            return userInfoList;
        }
    }
 
    public UserInfo getUserInfo(final int pUserId){
        synchronized (sLock) {
            UserInfo userInfo = null;
            try {
                String selection = DBData.USER_ID + " = ? ";
                String[] whereArgs = new String[] { String.valueOf(pUserId)};
                Cursor cursor = mContext.getContentResolver().query(mUri, null, selection, whereArgs, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()){
                        userInfo = toUserInfo(cursor);
                    }
                    cursor.close();
                }
 
            } catch (Exception e) {
                Log.i(TAG, "queryOne:Exception:" + e.toString());
            } catch (Error e) {
                Log.i(TAG, "queryOne:Error:" + e.toString());
            }
            return userInfo;
        }
    }
 
    public void dropTable() {
        synchronized (sLock) {
            try {
                String sql_drop_table = "DROP TABLE IF EXISTS " + DBData.TABLE_USER;
                mContext.getContentResolver().delete(mRawUri, sql_drop_table, null);
            } catch (Exception e) {
                Log.i(TAG, "dropTable:Error:" + e.toString());
            } catch (Error e) {
                Log.i(TAG, "dropTable:Error:" + e.toString());
            }
        }
    }
 
    private ContentValues toContentValues(ContentValues pCV, UserInfo pUserInfo) {
        if (pCV == null || pUserInfo == null){
            return pCV;
        }
        pCV.clear();
        pCV.put(DBData.USER_ID, pUserInfo.getUserId());
        pCV.put(DBData.USER_NICK_NAME, pUserInfo.getNickname());
        pCV.put(DBData.USER_PROFILE_PIC_URL, pUserInfo.getProfilePicUrl());
        pCV.put(DBData.USER_PHONE_NUM, pUserInfo.getPhoneNum());
        pCV.put(DBData.USER_EMAIL, pUserInfo.getEmail());
        pCV.put(DBData.USER_ADDRESS, pUserInfo.getAddress());
        return pCV;
    }
 
    private UserInfo toUserInfo(Cursor pCursor){
        UserInfo userInfo = new UserInfo();
        if (pCursor == null){
            return userInfo;
        }
        userInfo.setAutoId(pCursor.getInt(pCursor.getColumnIndex(DBData.USER_AUTO_ID)));
        userInfo.setUserId(pCursor.getInt(pCursor.getColumnIndex(DBData.USER_ID)));
        userInfo.setNickname(pCursor.getString(pCursor.getColumnIndex(DBData.USER_NICK_NAME)));
        userInfo.setProfilePicUrl(pCursor.getString(pCursor.getColumnIndex(DBData.USER_PROFILE_PIC_URL)));
        userInfo.setPhoneNum(pCursor.getString(pCursor.getColumnIndex(DBData.USER_PHONE_NUM)));
        userInfo.setEmail(pCursor.getString(pCursor.getColumnIndex(DBData.USER_EMAIL)));
        userInfo.setAddress(pCursor.getString(pCursor.getColumnIndex(DBData.USER_ADDRESS)));
        return userInfo;
    }
}

7.其中用到的UserInfo.java

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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
public class UserInfo implements Parcelable {
    private int mAutoId;
    private int mUserId;
    private String mNickname;
    private String mProfilePicUrl;
    private String mPhoneNum;
    private String mEmail;
    private String mAddress;
 
    public UserInfo(int userId, String nickname, String profilePicUrl, String phoneNum, String email, String address) {
        mUserId = userId;
        mNickname = nickname;
        mProfilePicUrl = profilePicUrl;
        mPhoneNum = phoneNum;
        mEmail = email;
        mAddress = address;
    }
 
    public int getAutoId() {
        return mAutoId;
    }
 
    public void setAutoId(int autoId) {
        mAutoId = autoId;
    }
 
    public int getUserId() {
        return mUserId;
    }
 
    public void setUserId(int userId) {
        mUserId = userId;
    }
 
    public String getNickname() {
        return mNickname;
    }
 
    public void setNickname(String nickname) {
        mNickname = nickname;
    }
 
    public String getProfilePicUrl() {
        return mProfilePicUrl;
    }
 
    public void setProfilePicUrl(String profilePicUrl) {
        mProfilePicUrl = profilePicUrl;
    }
 
    public String getPhoneNum() {
        return mPhoneNum;
    }
 
    public void setPhoneNum(String phoneNum) {
        mPhoneNum = phoneNum;
    }
 
    public String getEmail() {
        return mEmail;
    }
 
    public void setEmail(String email) {
        mEmail = email;
    }
 
    public String getAddress() {
        return mAddress;
    }
 
    public void setAddress(String address) {
        mAddress = address;
    }
 
 
    @Override
    public int describeContents() {
        return 0;
    }
 
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.mAutoId);
        dest.writeInt(this.mUserId);
        dest.writeString(this.mNickname);
        dest.writeString(this.mProfilePicUrl);
        dest.writeString(this.mPhoneNum);
        dest.writeString(this.mEmail);
        dest.writeString(this.mAddress);
    }
 
    public UserInfo() {
    }
 
    protected UserInfo(Parcel in) {
        this.mAutoId = in.readInt();
        this.mUserId = in.readInt();
        this.mNickname = in.readString();
        this.mProfilePicUrl = in.readString();
        this.mPhoneNum = in.readString();
        this.mEmail = in.readString();
        this.mAddress = in.readString();
    }
 
    public static final Creator<UserInfo> CREATOR = new Creator<UserInfo>() {
        @Override
        public UserInfo createFromParcel(Parcel source) {
            return new UserInfo(source);
        }
 
        @Override
        public UserInfo[] newArray(int size) {
            return new UserInfo[size];
        }
    };
 
    @Override
    public String toString() {
        return "UserInfo{" +
                "mAutoId=" + mAutoId +
                ", mUserId=" + mUserId +
                ", mNickname='" + mNickname + '\'' +
                ", mProfilePicUrl='" + mProfilePicUrl + '\'' +
                ", mPhoneNum='" + mPhoneNum + '\'' +
                ", mEmail='" + mEmail + '\'' +
                ", mAddress='" + mAddress + '\'' +
                '}';
    }
}

8.测试代码

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
public class SampleTask implements Runnable {
    private static final String TAG = SampleTask.class.getSimpleName();
    Handler mHandler;
    Context mContext;
 
    public SampleTask(Context context, Handler handler) {
        super();
        mHandler = handler;
        mContext = context;
    }
 
    @Override
    public void run() {
        try {
            // 模拟执行某项任务,下载等
            //Thread.sleep(5000);
            // 任务完成后通知activity更新UI
            //nickname, String profilePicUrl, String phoneNum, String email, String address
            List<UserInfo> userInfoList = new ArrayList<>();
            for (int i = 0; i < 10; i++){
                UserInfo userInfo = new UserInfo(10000 +i, "于" + i, "http://www.aoaoyi.com/" + i, "1883807***" + i, "1360***"+ i + "@qq.com", "aoaoyi" + i);
                userInfoList.add(userInfo);
            }
            UserInfoDao userInfoDao = new UserInfoDao(mContext);
            userInfoDao.insertList(userInfoList);
 
            List<UserInfo> userInfoList1 = userInfoDao.getUserInfoList();
            for (UserInfo userInfo : userInfoList1){
                Log.i(TAG, userInfo.toString());
            }
 
            Message msg = prepareMessage("task completed!");
            // message将被添加到主线程的MQ中
            mHandler.sendMessageDelayed(msg, 5000);
        } catch (Exception e) {
            Log.d(TAG, "interrupted!");
        }
    }
 
    private Message prepareMessage(String str) {
        Message result = mHandler.obtainMessage();
        Bundle data = new Bundle();
        data.putString("message", str);
        result.setData(data);
        return result;
    }
}
到这里,ContentProvider介绍也就结束了。
希望大家继续阅读下面的文章,这样更能提高大家对知识的掌握:
希望大家共同进步,早日找到一份理想的工作,实现财务自由。