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相关推荐

  1. C#中同一解决方案下,一个项目调用另一个项目中的窗体

    在实际应用中,一个程序大多是多人共同完成,如果最初对窗体命名时没沟通好出现重名,这样直接在项目中导入窗体(添加现有项)容易造成调用混乱.而且大多时候各自开发的是独立模块,单纯导入窗体而不导入相应的输入 ...

  2. Spring事务管理嵌套事务详解 : 同一个类中,一个方法调用另外一个有事务的方法

    Spring 事务机制回顾 Spring事务一个被讹传很广说法是:一个事务方法不应该调用另一个事务方法,否则将产生两个事务.  结果造成开发人员在设计事务方法时束手束脚,生怕一不小心就踩到地雷.    ...

  3. php调用另一个php文件里的变量的值,thinkphp中一个方法调用另一个步骤的变量

    thinkphp中一个方法调用另一个方法的变量 //实例化上传类 public function upload() { $upload = new Upload(); $upload->maxS ...

  4. spring同一个类中,一个方法调用另外一个注解(@Transactional)方法时,注解失效

    title: "spring同一个类中,一个方法调用另外一个注解(@Transactional)方法时,注解失效" url: "https://wsk1103.githu ...

  5. 在同一个类中,一个方法调用另外一个有注解(比如@Async,@Transational)的方法,注解失效的原因和解决方法

    在同一个类中,一个方法调用另外一个有注解(比如@Async,@Transational)的方法,注解失效的原因和解决方法 参考文章: (1)在同一个类中,一个方法调用另外一个有注解(比如@Async, ...

  6. SpringCloud实现一个模块调用另一个模块的服务

    SpringCloud实现一个模块调用另一个模块的服务 简介 基于SpringCloud框架搭建的项目,不同模块之间是无法调用各自的服务的,但是经常我们需要使用这样的模式去开发,那么如何实现不同模块之 ...

  7. C语言初级学习---一个文件调用另一个源文件函数!

    文章目录 C语言初级学习-------如何从一个文件调用另一个源文件的函数! C语言初级学习-------如何从一个文件调用另一个源文件的函数! 在很多时候,我们写的代码过多,但是为了高效的修改及管理 ...

  8. mave工程中的一个类调用另一个聚合工程的一个类_求求你,别再写上千行的类了好吗...

    专注于Java领域优质技术,欢迎关注 作者:橙味菌 最近在对已有项目进行扩展的时候,发现要改动的一个类它长766行,开放了近40个public接口,我流着泪把它给改完了.为了防止这样的惨剧再次发生在我 ...

  9. 对一个项目如何写一个方案?

    如何对给定的需求进行分析并给出一个解决方案呢? 事情要从老师给了我一个项目开始说起.项目的内容就不必赘述了,作为老师新收的一名小小研究生,确实能力很差.前前后后和老师进行了多次的沟通.修改,可以都无济 ...

最新文章

  1. java Character类的一些简单的方法
  2. linux追踪tomcat报错信息,linux下tomcat服务的启动、关闭与错误跟踪
  3. FOC驱动器和无刷电调的区别
  4. WPF Wonders: Transformations (and Robots!)
  5. 最近面试一些厂的面经整理(阿里,腾讯,字节等)
  6. Java if语句深度解析
  7. SQLServer约束介绍
  8. C++中 list与vector的区别
  9. clistctrl控件最后插入在后面_老板让我把图片放到Excel表格中,批量插入效率高...
  10. Linux 5.10将解决2038年问题
  11. weblogic8.1在myeclipse中启动正常,在单独的weblogic中无法正常启动的解决方案.
  12. Python-datetime模块
  13. css3动画结束捕捉事件整理
  14. PPT幻灯片放映计时器
  15. linux程序性能分析工具stap,《面向应用开发者的系统指南》CPU篇之使用systemtap分析进程的行为...
  16. S一文读懂应力集中与应力奇异
  17. 电信套餐2020一览表_移动联通接连放大招,5G 套餐要降价?
  18. 数据中心IDC产业研究报告:碳中和背景下,IDC产业链的破局之路
  19. http://blog.csdn.net/pizi0475/article/details/7768597
  20. 1996年图灵奖--阿米尔·伯努利简介

热门文章

  1. 二进制蚁群算法【源码实现】
  2. Java 设计模式之模板方法模式
  3. VTK:定向箭头用法实战
  4. OpenCASCADE:Modeling Algorithms模块标准拓扑对象
  5. wxWidgets:wxLogChain类用法
  6. boost::hana::any用法的测试程序
  7. boost::intrusive::set用法的测试程序
  8. GDCM:把DICOM文件存在vector<char>里面的测试程序
  9. VTK:Utilities之BrownianPoints
  10. OpenCV使用GDAL读取地理空间栅格文件