09_Android中ContentProvider和Sqllite混合操作,一个项目调用另外一个项目的ContentProvider
1、 编写ContentPrivider提供者的Android应用
清单文件
|
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.itheima28.sqlitedemo" android:versionCode="1" android:versionName="1.0" > <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.itheima28.sqlitedemo" > </instrumentation> <permission android:name="aa.bb.cc.read" ></permission> <permission android:name="aa.bb.cc.write" ></permission> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <uses-library android:name="android.test.runner" /> <activity android:name="com.itheima28.sqlitedemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!—注意加上:android:exported="true",通过它来避免出错-à <provider android:name=".providers.PersonContentProvider" android:authorities="com.itheima28.sqlitedemo.providers.PersonContentProvider" android:readPermission="aa.bb.cc.read" android:writePermission="aa.bb.cc.write" android:exported="true"> </provider> </application> </manifest> |
2 编写实体Person
|
package com.itheima28.sqlitedemo.entities; publicclass Person { privateintid; private String name; privateintage; publicint getId() { returnid; } publicvoid setId(int id) { this.id = id; } public String getName() { returnname; } publicvoid setName(String name) { this.name = name; } publicint getAge() { returnage; } publicvoid setAge(int age) { this.age = age; } public Person() { super(); // TODO Auto-generated constructor stub } public Person(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } @Override public String toString() { return"Person [id=" + id + ", name=" + name + ", age=" + age + "]"; } } |
3 编写dbHelper
|
package com.itheima28.sqlitedemo.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * @author toto * 数据库帮助类,用于创建和管理数据库的 */ public class PersonSQLiteOpenHelper extends SQLiteOpenHelper{ private static final String TAG = "PersonSQLiteOpenHelper"; public PersonSQLiteOpenHelper(Context context){ super(context, "itheima28.db", null, 2); } /** * 数据库第一次创建时回调此方法 * 初始化表 */ @Override public void onCreate(SQLiteDatabase db) { //操作数据 String sql = "create table person(_id integer primary key, name varchar(20), age integer);"; db.execSQL(sql); } /** * 数据库的版本号更新时回调此方法 * 更新数据库的内容(删除表,添加表,修改表) */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion == 1 && newVersion == 2) { Log.i(TAG, "数据库更新啦"); db.execSQL("alter table person add balance integer;"); } } } |
4 编写通过sql的Dao操作类
|
package com.itheima28.sqlitedemo.dao; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.itheima28.sqlitedemo.db.PersonSQLiteOpenHelper; import com.itheima28.sqlitedemo.entities.Person; public class PersonDao { private PersonSQLiteOpenHelper mOpenHelper; // 数据库的帮助类对象 public PersonDao(Context context) { mOpenHelper = new PersonSQLiteOpenHelper(context); } /** * 添加到person表一条数据 * @param person */ public void insert(Person person) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); if(db.isOpen()) { // 如果数据库打开, 执行添加的操作 // 执行添加到数据库的操作 db.execSQL("insert into person(name, age) values(?, ?);", new Object[]{person.getName(), person.getAge()}); db.close(); // 数据库关闭 } } /** * 更据id删除记录 * @param id */ public void delete(int id) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // 获得可写的数据库对象 if(db.isOpen()) { // 如果数据库打开, 执行添加的操作 db.execSQL("delete from person where _id = ?;", new Integer[]{id}); db.close(); // 数据库关闭 } } /** * 根据id找到记录, 并且修改姓名 * @param id * @param name */ public void update(int id, String name) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); if(db.isOpen()) { // 如果数据库打开, 执行添加的操作 db.execSQL("update person set name = ? where _id = ?;", new Object[]{name, id}); db.close(); // 数据库关闭 } } public List<Person> queryAll() { SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获得一个只读的数据库对象 if(db.isOpen()) { Cursor cursor = db.rawQuery("select _id, name, age from person;", null); if(cursor != null && cursor.getCount() > 0) { List<Person> personList = new ArrayList<Person>(); int id; String name; int age; while(cursor.moveToNext()) { id = cursor.getInt(0); // 取第0列的数据 id name = cursor.getString(1); // 取姓名 age = cursor.getInt(2); // 取年龄 personList.add(new Person(id, name, age)); } db.close(); return personList; } db.close(); } return null; } /** * 根据id查询人 * @param id * @return */ public Person queryItem(int id) { SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获得一个只读的数据库对象 if(db.isOpen()) { Cursor cursor = db.rawQuery("select _id, name, age from person where _id = ?;", new String[]{id + ""}); if(cursor != null && cursor.moveToFirst()) { int _id = cursor.getInt(0); String name = cursor.getString(1); int age = cursor.getInt(2); db.close(); return new Person(_id, name, age); } db.close(); } return null; } } |
5 编写不是通过sql的操作类
|
package com.itheima28.sqlitedemo.dao; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.itheima28.sqlitedemo.db.PersonSQLiteOpenHelper; import com.itheima28.sqlitedemo.entities.Person; public class PersonDao2 { private static final String TAG = "PersonDao2"; private PersonSQLiteOpenHelper mOpenHelper; // 数据库的帮助类对象 public PersonDao2(Context context) { mOpenHelper = new PersonSQLiteOpenHelper(context); } /** * 添加到person表一条数据 * @param person */ public void insert(Person person) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); if(db.isOpen()) { // 如果数据库打开, 执行添加的操作 ContentValues values = new ContentValues(); values.put("name", person.getName()); // key作为要存储的列名, value对象列的值 values.put("age", person.getAge()); long id = db.insert("person", "name", values); Log.i(TAG, "id: " + id); db.close(); // 数据库关闭 } } /** * 更据id删除记录 * @param id */ public void delete(int id) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // 获得可写的数据库对象 if(db.isOpen()) { // 如果数据库打开, 执行添加的操作 String whereClause = "_id = ?"; String[] whereArgs = {id + ""}; int count = db.delete("person", whereClause, whereArgs); Log.i(TAG, "删除了: " + count + "行"); db.close(); // 数据库关闭 } } /** * 根据id找到记录, 并且修改姓名 * @param id * @param name */ public void update(int id, String name) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); if(db.isOpen()) { // 如果数据库打开, 执行添加的操作 ContentValues values = new ContentValues(); values.put("name", name); int count = db.update("person", values, "_id = ?", new String[]{id + ""}); Log.i(TAG, "修改了: " + count + "行"); db.close(); // 数据库关闭 } } public List<Person> queryAll() { SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获得一个只读的数据库对象 if(db.isOpen()) { String[] columns = {"_id", "name", "age"}; // 需要的列 String selection = null; // 选择条件, 给null查询所有 String[] selectionArgs = null; // 选择条件的参数, 会把选择条件中的? 替换成数据中的值 String groupBy = null; // 分组语句 group by name String having = null; // 过滤语句 String orderBy = null; // 排序 Cursor cursor = db.query("person", columns, selection, selectionArgs, groupBy, having, orderBy); int id; String name; int age; if(cursor != null && cursor.getCount() > 0) { List<Person> personList = new ArrayList<Person>(); while(cursor.moveToNext()) { // 向下移一位, 知道最后一位, 不可以往下移动了, 停止. id = cursor.getInt(0); name = cursor.getString(1); age = cursor.getInt(2); personList.add(new Person(id, name, age)); } db.close(); return personList; } db.close(); } return null; } /** * 根据id查询人 * @param id * @return */ public Person queryItem(int id) { SQLiteDatabase db = mOpenHelper.getReadableDatabase(); // 获得一个只读的数据库对象 if(db.isOpen()) { String[] columns = {"_id", "name", "age"}; // 需要的列 String selection = "_id = ?"; // 选择条件, 给null查询所有 String[] selectionArgs = {id + ""}; // 选择条件的参数, 会把选择条件中的? 替换成数据中的值 String groupBy = null; // 分组语句 group by name String having = null; // 过滤语句 String orderBy = null; // 排序 Cursor cursor = db.query("person", columns, selection, selectionArgs, groupBy, having, orderBy); if(cursor != null && cursor.moveToFirst()) { // cursor对象不为null, 并且可以移动到第一行 int _id = cursor.getInt(0); String name = cursor.getString(1); int age = cursor.getInt(2); db.close(); return new Person(_id, name, age); } db.close(); } return null; } } |
6 编写通过sql操作数据库的单元测试
|
package com.itheima28.sqlitedemo.test; import java.util.List; import android.database.sqlite.SQLiteDatabase; import android.test.AndroidTestCase; import android.util.Log; import com.itheima28.sqlitedemo.dao.PersonDao; import com.itheima28.sqlitedemo.db.PersonSQLiteOpenHelper; import com.itheima28.sqlitedemo.entities.Person; public class TestCase extends AndroidTestCase { private static final String TAG = "TestCase"; public void test() { // 数据库什么时候创建 PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext()); // 第一次连接数据库时创建数据库文件. onCreate会被调用 openHelper.getReadableDatabase(); } public void testInsert() { PersonDao dao = new PersonDao(getContext()); for (int i = 0; i < 20; i++) { dao.insert(new Person(0, "冠希" + i, 10 + i)); } } public void testDelete() { PersonDao dao = new PersonDao(getContext()); dao.delete(1); } public void testUpdate() { PersonDao dao = new PersonDao(getContext()); dao.update(3, "凤姐"); } public void testQueryAll() { PersonDao dao = new PersonDao(getContext()); List<Person> personList = dao.queryAll(); for (Person person : personList) { Log.i(TAG, person.toString()); } } public void testQueryItem() { PersonDao dao = new PersonDao(getContext()); Person person = dao.queryItem(4); Log.i(TAG, person.toString()); } public void testTransaction() { PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext()); SQLiteDatabase db = openHelper.getWritableDatabase(); if(db.isOpen()) { try { // 开启事务 db.beginTransaction(); // 1. 从张三账户中扣1000块钱 db.execSQL("update person set balance = balance - 1000 where name = 'zhangsan';"); // ATM机, 挂掉了. // int result = 10 / 0; // 2. 向李四账户中加1000块钱 db.execSQL("update person set balance = balance + 1000 where name = 'lisi';"); // 标记事务成功 db.setTransactionSuccessful(); } finally { // 停止事务 db.endTransaction(); } db.close(); } } public void testTransactionInsert() { PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext()); SQLiteDatabase db = openHelper.getWritableDatabase(); if(db.isOpen()) { // 1. 记住当前的时间 long start = System.currentTimeMillis(); // 2. 开始添加数据 try { db.beginTransaction(); for (int i = 0; i < 10000; i++) { db.execSQL("insert into person(name, age, balance) values('wang" + i + "', " + (10 + i) + ", " + (10000 + i) + ")"); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } // 3. 记住结束时间, 计算耗时时间 long end = System.currentTimeMillis(); long diff = end - start; Log.i(TAG, "耗时: " + diff + "毫秒"); db.close(); } } } |
7 编写不是通过sql操作的数据库的单元测试
|
package com.itheima28.sqlitedemo.test; import java.util.List; import android.test.AndroidTestCase; import android.util.Log; import com.itheima28.sqlitedemo.dao.PersonDao2; import com.itheima28.sqlitedemo.db.PersonSQLiteOpenHelper; import com.itheima28.sqlitedemo.entities.Person; public class TestCase2 extends AndroidTestCase { private static final String TAG = "TestCase"; public void test() { // 数据库什么时候创建 PersonSQLiteOpenHelper openHelper = new PersonSQLiteOpenHelper(getContext()); // 第一次连接数据库时创建数据库文件. onCreate会被调用 openHelper.getReadableDatabase(); } public void testInsert() { PersonDao2 dao = new PersonDao2(getContext()); dao.insert(new Person(0, "zhouqi", 88)); } public void testDelete() { PersonDao2 dao = new PersonDao2(getContext()); dao.delete(8); } public void testUpdate() { PersonDao2 dao = new PersonDao2(getContext()); dao.update(3, "fengjie"); } public void testQueryAll() { PersonDao2 dao = new PersonDao2(getContext()); List<Person> personList = dao.queryAll(); for (Person person : personList) { Log.i(TAG, person.toString()); } } public void testQueryItem() { PersonDao2 dao = new PersonDao2(getContext()); Person person = dao.queryItem(4); Log.i(TAG, person.toString()); } } |
8 Activity不用写东西
二、第二个测试项目调用第一个项目的ContentProvider
清单文件如下:
|
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.itheima28.othercontentprovider" android:versionCode="1" android:versionName="1.0" > <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.itheima28.othercontentprovider"> </instrumentation> <uses-permission android:name="aa.bb.cc.read"/> <uses-permission android:name="aa.bb.cc.write"/> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <uses-library android:name="android.test.runner"/> <activity android:name="com.itheima28.othercontentprovider.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
2 Activity不用写
3 单元测试类如下:
|
package com.itheima28.othercontentprovider; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.test.AndroidTestCase; import android.util.Log; publicclass TextCase extends AndroidTestCase { privatestaticfinal String TAG = "TextCase"; publicvoid testInsert() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/insert"); //内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); ContentValues values = new ContentValues(); values.put("name", "fengjie"); values.put("age", 90); uri = resolver.insert(uri, values); Log.i(TAG, "uri:" + uri); long id = ContentUris.parseId(uri); Log.i(TAG, "添加到:" + id); } publicvoid testDelete() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/delete"); //内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); String where = "_id = ?"; String[] selectionArgs = {"21"}; int count = resolver.delete(uri, where, selectionArgs); Log.i(TAG, "删除行:" + count); } publicvoid testUpdate() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/update"); //内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); ContentValues values = new ContentValues(); values.put("name", "lisi"); int count = resolver.update(uri, values,"_id = ?", new String[]{"20"}); Log.i(TAG, "更新行:" + count); } publicvoid testQueryAll() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/queryAll"); //内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = resolver.query(uri, new String[]{"_id", "name", "age"}, null, null, "_id desc"); if (cursor != null && cursor.getCount() > 0) { int id; String name; int age; while(cursor.moveToNext()){ id = cursor.getInt(0); name = cursor.getString(1); age = cursor.getInt(2); Log.i(TAG, "id: " + id + ", name: " + name + ", age: " + age); } cursor.close(); } } publicvoid testQuerySingleItem() { Uri uri = Uri.parse("content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/#"); // 在uri的末尾添加一个id content://com.itheima28.sqlitedemo.providers.PersonContentProvider/person/query/20 uri = ContentUris.withAppendedId(uri, 20); //内容提供者访问对象 ContentResolver resolver = getContext().getContentResolver(); Cursor cursor = resolver.query(uri, new String[]{"_id", "name", "age"}, null, null, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(0); String name = cursor.getString(1); int age = cursor.getInt(2); cursor.close(); Log.i(TAG, "id: " + id + ", name: " + name + ", age: " + age); } } } |
09_Android中ContentProvider和Sqllite混合操作,一个项目调用另外一个项目的ContentProvider的更多相关文章
- Eclipse中一个项目调用另一个项目的资源
如果一个项目A想要引用另一个项目B的资源的话,按照一下步骤进行设置: 右键点击项目A---->>>Build Path--->>>Configure Build P ...
- vue中methods一个方法调用另外一个方法
转自http://blog.csdn.net/zhangjing1019/article/details/77942923 vue在同一个组件内: methods中的一个方法调用methods中的另外 ...
- WinForm中一个窗体调用另一个窗体
[转] WinForm中一个窗体调用另一个窗体的控件和事件的方法(附带源码) //如果想打开一个 Form2 的窗体类,只需要: Form2 form = new Form2(); //有没有参数得看 ...
- 在同一个类中,一个方法调用另外一个有注解(比如@Async,@Transational)的方法,注解失效的原因和解决方法
参考原贴地址:https://blog.csdn.net/clementad/article/details/47339519 在同一个类中,一个方法调用另外一个有注解(比如@Async,@Trans ...
- eclipse中一个项目引用另一个项目的方法(申明:来源于网络)
eclipse中一个项目引用另一个项目的方法(申明:来源于网络) 地址:http://blog.csdn.net/a942980741/article/details/39990699
- 【转】在同一个类中,一个方法调用另外一个有注解(比如@Async,@Transational)的方法,注解失效的原因和解决方法
参考 原文链接 @Transactional does not work on method level 描述 在同一个类中,一个方法调用另外一个有注解(比如@Async,@Transational) ...
- Android studio 一个项目引入另一个项目作为Libary
1.在我们开发Android项目时,有时需要一个项目作为另一个项目的工具类的引用,这样就需要配置下,使得MyLibrary到MyApplication作为一个module. 我们直接截图上步骤: 1. ...
- C#一个窗体调用另一个窗体的方法
一个窗体调用另一个窗体的方法:例如:窗体B要调用窗体A中的方法1.首先在窗体A中将窗体A设为静态窗体public static FormA m_formA; //设此窗体为静态,其他窗体可调用此 ...
- Qt一个project调用还有一个project的类成员变量
一句两句话已经不能表达如今的激动情绪了.唯有感叹知识的博大精深,并把感叹转变为文字. 同一个project调用其它类成员变量很easy. 如: 定义 Test1.h中申明成员变量 class A { ...
随机推荐
- Linux中MySQL忽略表中字段大小写
linux 下,mysql 的表面默认是区分大小写的,windows 下默认不区分大小写,我们大多数在windows 下开发,之后迁移到linux(特别是带有Hibernate的工程),可以修改配置是 ...
- Rails 4.0 bundle exec rspec spec/requests/xxx 测试失败的解决
rails项目没有使用默认的单元测试包,而是使用了rspec-rails来测试. 按照文档说明首先生成对应的测试文件: rails generate integration_test xxx invo ...
- npm killed有可能是内存不够, 为Ubuntu增加swap
参考 http://www.cnblogs.com/owenyang/p/4282283.html 查看swap使用策略 cat /proc/sys/vm/swappiness 0代表尽量使用物理内存 ...
- Android TV开发总结(三)构建一个TV app的焦点控制及遇到的坑
转载请把头部出处链接和尾部二维码一起转载,本文出自逆流的鱼yuiop:http://blog.csdn.net/hejjunlin/article/details/52835829 前言:上篇中,&l ...
- 制作pypi上的安装库
下载地址 如何制作分发工具呢 setuppy 源码包 其他文件 制作过程 首先上场的肯定是setuppy了如下 然后是LICENCE 注册 测试 总结 自从接触Python以来也有几个月了,虽然主要的 ...
- 一个环形公路,上面有N个站点,A1, ..., AN,其中Ai和Ai+1之间的距离为Di,AN和A1之间的距离为D0。 高效的求第i和第j个站点之间的距离,空间复杂度不超过O(N)。
//点数 #define N 10 //点间距 int D[N]; //A1到每个Ai的距离 int A1ToX[N]; void preprocess() { srand(time(0)); //随 ...
- 用Python最原始的函数模拟eval函数的浮点数运算功能
前几天看一个网友提问,如何计算'1+1'这种字符串的值,不能用eval函数. 我仿佛记得以前新手时,对这个问题完全不知道如何下手. 我觉得处理括号实在是太复杂了,多层嵌套括号怎么解析呢?一些多余的括号 ...
- Android必知必会-发布开源 Android 项目注意事项
如果移动端访问不佳,请使用 –> Github版 1. 合理配置 .gitignore 文件 配置 .gitignore 可以排除一些非必要文件和保护保密信息,下面是在项目根目录下 .gitig ...
- Xcode的playground中对于SpriteKit物理对象的更新为何无效
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 为了便于SpriteKit中物理行为的调试,我们可以借助于Xc ...
- [Ubuntu] 14.04 关闭桌面
一直在用Ubuntu的桌面来做调试环境,最近发现桌面会有崩溃的时候,占用资源也比较大,所以想把桌面关闭,只用command界面. 我的系统是Ubuntu14.04 Ctrl+Alt+F1 可以转到命令 ...