功能:跨app访问本app数据库一些基本操做java
本app中:
android
一、在配置清单里配置权限和自定义ContentProvider对外暴露给其余应用访问的路径sql
代码数据库
<?xml version="1.0" encoding="utf-8"?>app
<manifest xmlns:android="http://schemas.android.com/apk/res/android"框架
package="com.example.contentprovider_custom"ide
android:versionCode="1"工具
android:versionName="1.0" >单元测试
<uses-sdk测试
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".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>
<!-- 自定义ContentProvider name :包名.类名 -->
<!-- 自定义ContentProvider authirities :最好 是包名.类名 也能够是任意 -->
<!-- 自定义ContentProvider exported :是否容许别的app访问 -->
<provider
android:name="com.example.contentprovider_custom.Custom"
android:authorities="com.example.contentprovider_custom.custom"
android:exported="true" >
</provider>
</application>
=======================
//一共有3个类一个一、MainActivity.java类二、Sqlite_table.java类三、Custom.java类
二、MainActivity.java类
代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
//这里没什么功能 只是简单说明一些自定义ContentProvider
============================
三、Sqlite_table类 -- 本app建立的数据库(本app没有数据库才建立有了直接能够使用)
代码
public class Sqlite_table extends SQLiteOpenHelper {
private static final String DBNAME = "student.db";
private static final int VERSION = 1;
public Sqlite_table(Context context) {
super(context, DBNAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table student(s_id integer primary key autoincrement not null," +
"s_name varchar(20) not null," +
"s_age varchar(2) not null," +
"s_address varchar(40) not null," +
"s_classname varchar(20) not null)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("drop table exists student");
onCreate(db);
}
}
}
======================
四、Custom类 -- 其余应用对本app数据库基本操做
代码
//自定义ContentProvider 要继承ContentProvider类
public class Custom extends ContentProvider {
//在功能清单配置的 -- URI 的autauthorities部分
private static String autauthorities = "com.example.contentprovider_custom.custom";
//在声明一个工具类对象
private static UriMatcher uriMatcher;//匹配URI的匹配器
static{//静态代码块
uriMatcher = new UriMatcher(-1);//若是uri匹配不上 返回-1
//第一个参数 -- uri部分
//第二份参数 -- path -- 最好填数据库表名
//第三个参数 -- 若是uri匹配 就返回 匹配成功码 code
uriMatcher.addURI(autauthorities, "student", 100);//code随便定义
uriMatcher.addURI(autauthorities, "student/*", 101);//斜杠后面跟着*表明文本标志
uriMatcher.addURI(autauthorities, "stu/#", 102);//斜杠后面跟着#号表明数字
}
private Sqlite_table sqlite_table ;
@Override
public boolean onCreate() {
sqlite_table = new Sqlite_table(getContext());
return false;
}
//-----------------------如下是重写对sqlite数据库基本操做的方法(给其余应用操做)-----------------------
@Override//查询本app数据库
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor cursor = null;
SQLiteDatabase db = sqlite_table.getReadableDatabase();
switch(uriMatcher.match(uri)){
case 100://uri匹配成功
cursor = db.query("student", projection, selection, selectionArgs, null, null,sortOrder);
break;
case 101:
String keyword = uri.getLastPathSegment();//用getLastPathSegment方法 得到文本标志
//模糊查询 名字第一个是 ...
cursor = db.query("student", projection, "s_name like ?", new String[]{keyword + "%"}, null,null,null);
break;
case 102:
long score = ContentUris.parseId(uri);//获取uri后面的数字
cursor = db.query("student", projection, "score = ?", new String[]{score + ""}, null, null, null);
break;
}
return cursor;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override//添加数据到本app数据库
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = sqlite_table.getReadableDatabase();
Uri insert_uri = null;
switch(uriMatcher.match(uri)){
case 100:
long rowid = db.insert("student", null, values);//返回插入的行
insert_uri = ContentUris.withAppendedId(uri,rowid);//用工具类ContentUris拼接返回来的行号 变成插入新数据的uri
break;
}
return insert_uri;
}
@Override//删除
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = sqlite_table.getReadableDatabase();
int rownum = 0;
switch(uriMatcher.match(uri)){
case 100:
rownum = db.delete("student", selection, selectionArgs);
break;
}
return rownum;
}
@Override//修改
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = sqlite_table.getReadableDatabase();
int rows = 0;
switch(uriMatcher.match(uri)){
case 100:
rows = db.update("student", values, selection, selectionArgs);
break;
}
return rows;
}
}
==========================================
//其余应用操做本app(这里使用测试类测试)
五、测试类要在配置清单里添加相应的权限和引入android测试框架
代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.contentprovider.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<!-- 添加权限 对数据库的操做 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 引入android单元测试的框架 targetPackage 是该app的包名 -->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.contentprovider.test">
</instrumentation>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".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>
<!-- 单元测试的依赖包 -->
<uses-library
android:name="android.test.runner"/>
</application>
</manifest>
=========================
六、配置清单部署好后,创建一个Test_ContentProvider测试类
代码
public class Test_ContentProvider extends AndroidTestCase {
// -- content://后面接的字符串在要测试自定义ContentProvider 应用的清单文件里
// -- content:// 这是固定的
// authorities -- uri部分
// 后面跟着的是数据库的表名
private String uri = "content://com.example.contentprovider_custom.custom/student";
//查询数据
//测试方法能够直接运行
public void testQuery() {
ContentResolver resolver = getContext().getContentResolver();
Cursor cursor = resolver.query(Uri.parse(uri), new String[] { "s_name", "s_age",
"s_address", "s_classname" }, null, null,
null);
while(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("s_name"));
String age = cursor.getString(cursor.getColumnIndex("s_age"));
String address = cursor.getString(cursor.getColumnIndex("s_address"));
String classname = cursor.getString(cursor.getColumnIndex("s_classname"));
Log.i("data", name + "," + age + "," + address + "," + classname);
}
cursor.close();
}
//添加数据
public void testInsert(){
ContentResolver resolver = getContext().getContentResolver();
Log.i("data", "----------");
ContentValues values = new ContentValues();
values.put("s_name", "呵呵");
values.put("s_age", 18);
values.put("s_address", "广州天河区");
values.put("s_classname", "学前班");
Log.i("data", "vaules:" + values.toString());
resolver.insert(Uri.parse(uri), values );
}
}
=================
七、先运行ContentProvider应用 ,而后运行测试类的添加数据方法 往建立好的数据库添加数据
最后运行查询方法查询数据
效果图示例: