黑马程序员安卓教程:ContentProvider 基本使用

没有退路 分享 2020-06-22 下载文档

ContentProvider 基本使用

称 AppA)和内容访问者 B(简称 AppB)。在 AppA 中创建数据库 user.db,该 db 中有两张表,t_woman

和 t_man。AppA 通过内容提供者对外提供数据库中的数据。AppB 作为一个内容访问者,通过内容解析者(ContentResolver)实现对 AppA 中的数据进行增删改查功能。

为了演示 ContentProvider 的基本用法,在该节中我们将创建两个 Android 工程:01-内容提供者 A(简

1.2.1 创建工程 01-内容提供者A

一、在 AppA 中创建 MySQLiteOpenHelper 类

在该类中实现数据库和数据表的创建业务逻辑。

【文件 1-1】 MySQLiteOpenHelper.java

1. package com.example.contentProviderA;

2.

3. importandroid.content.Context;

4. importandroid.database.sqlite.SQLiteDatabase;

5. importandroid.database.sqlite.SQLiteDatabase.CursorFactory; 6. importandroid.database.sqlite.SQLiteOpenHelper; 7. /**

8. * 创建数据库user.db同时初始化表t_woman和t_man。 9. *

10. * @author wzy2016-1-24 11. * 12. */

3

13. public classMySQLiteOpenHelperextends SQLiteOpenHelper{ 14.

15. //数据库名称

16. private static final String DB_NAME= \17. //数据库版本号

18. private static final int VERSION =1; 19.

20. private MySQLiteOpenHelper(Contextcontext, Stringname, CursorFactory factory, 21. int version){ 22. 23. } 24.

25. publicMySQLiteOpenHelper(Context context){ 26. 27. } 28.

29. @Override

30. publicvoidonCreate(SQLiteDatabasedb){

31. Stringsql_woman=\t_woman(id integerprimarykey, 32. c_name varchar(10),c_phone varchar(20))\

33. Stringsql_man =\t_man(idinteger primarykey, 34. c_name varchar(10),c_phone varchar(20))\35. 36. 37. } 38.

39. @Override

db.execSQL(sql_woman); db.execSQL(sql_man);

this(context,DB_NAME, null, VERSION); super(context, name, factory,version);

40. publicvoidonUpgrade(SQLiteDatabase db,intoldVersion, int newVersion) {

41.

42. }

43.

44. }

45.

二、使用测试类初始化 user.db

为了让 MySQLiteOpenHelper.java 中 onCreate 方法被调用,我们可以采用一个测试类来实现,

当然使用其他方法也是可行的。这里使用测试类初始化 AppA 的数据库也是为了复习 Android Junit

Test 的使用。

创建测试类 MyTest.java,代码如【文件 1-2】所示。 【文件 1-2】 MyTest.java

1. package com.example.contentProviderA;

2.

3. importandroid.database.sqlite.SQLiteDatabase; 4. importandroid.test.AndroidTestCase;

4

5. /** 6. 7. 8. 9.

* 定义测试类,用于初始化user.db *

* @author wzy2016-1-24 *

10. */

11. publicclass MyTest extends AndroidTestCase { 12. 13. 14. 15. 16.

17.

publicvoidtest(){

/**

* 在AndroidTestCase类中可以直接使用getContext()方法获取到Context对象 */

MySQLiteOpenHelper sqLiteOpenHelperMySQLiteOpenHelper(getContext());

=

new

18. 19. 20. 21. } 22.

}

SQLiteDatabase writableDatabase sqLiteOpenHelper.getWritableDatabase(); writableDatabase.close();

=

在 AndroidManifest.xml 中添加测试指令集和测试库。 在 application 节点外添加指令集。

1. 2. 3.

android:name=\android:targetPackage=\

在 application 节点中添加测试库。

4.

万事俱备后一定记得运行一下该测试方法,看见如下绿条和数据库文件才行哦。

图 1-2数据库初始化完成


黑马程序员安卓教程:ContentProvider 基本使用 .doc 将本文的Word文档下载到电脑

下一篇:如何在体育教学中激发学生的兴趣

相关推荐
相关阅读
本类排行
× 游客快捷下载通道(下载后可以自由复制和排版)

下载本文档需要支付 7

支付方式:

开通VIP包月会员 特价:29元/月

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:xxxxxx QQ:xxxxxx