这里需要建立两个项目:SiYouShuJuKu(使用内容提供者暴露相关的操作),DQDYGApplication(使用内容解析者对第一个应用进行相关的解析)
A.第一个项目:SiYouShuJuKu
结构图如下:
AccountProvider:
package com.demo.siyoushujuku;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class AccountProvider extends ContentProvider {
//1.定义一个urimatcher 定义路径匹配器
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int QUERYSUCCESS = 0;
private static final int INSERTSUCCESS = 1;
private static final int UPDATESUCCESS = 2;
private static final int DELETESUCCESS = 3;
private MyOpenHelper myOpenHelper;
// c+s+U 变大写
//2.定义静态代码块 添加匹配规则
static {
/**
* authority:
* 要和你在清单文件定义的一样
*
* uri:http://com.provider/query
*
*
*/
sURIMatcher.addURI("com.provider", "query", QUERYSUCCESS);
sURIMatcher.addURI("com.provider", "insert", INSERTSUCCESS);
sURIMatcher.addURI("com.provider", "update", UPDATESUCCESS);
sURIMatcher.addURI("com.provider", "delete", DELETESUCCESS);
//3.写一个静态代码块 添加匹配规则
}
@Override
public boolean onCreate() {
myOpenHelper = new MyOpenHelper(getContext());
return false;
}
//查询
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
int code = sURIMatcher.match(uri);
if (code == QUERYSUCCESS) {
//说明路径匹配成功
// 把query方法实现一下 数据库查询 对数据库进行查询 想操作数据库
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
Cursor cursor = db.query("info", projection, selection, selectionArgs,
null, null, sortOrder
);
//注意cursor不能关 在这里
return cursor;
} else {
//路径不匹配
throw new IllegalArgumentException("哥们:您的路径不匹配 ,请检查路径");
}
// return null;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
int code = sURIMatcher.match(uri);
if(code == INSERTSUCCESS){
//操作数据库
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
//代表新插入行数的id
long insert = db.insert("info", null, values);
Uri uri2 = Uri.parse("com.insert/"+insert);
System.out.println("insert==>"+insert);
return uri2;
}else{
//路径不匹配
throw new IllegalArgumentException("姐们:您的路径不匹配 ,请检查路径");
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int code = sURIMatcher.match(uri);
if(code == DELETESUCCESS){
//说明路径匹配成功,对数据库进行删除的操作
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
//这里代表影响的行数
int delete = db.delete("info", selection, selectionArgs);
return delete;
}else{
//路径不匹配
throw new IllegalArgumentException("姐们:您的路径不匹配 ,请检查路径");
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int code = sURIMatcher.match(uri);
if(code == UPDATESUCCESS){
//说明路径匹配成功,对数据库进行删除的操作
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
//这里代表影响的行数
int update = db.update("info", values,selection, selectionArgs);
return update;
}else{
//路径不匹配
throw new IllegalArgumentException("姐们:您的路径不匹配 ,请检查路径");
}
}
}
MainActivity:
package com.demo.siyoushujuku;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyOpenHelper myOpenHelper = new MyOpenHelper(getApplicationContext());
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
Cursor cursor = db.query("info", null, null, null, null, null,
null
);
if (cursor!=null&&cursor.getCount()>0){
while (cursor.moveToNext()){
String name = cursor.getString(1);
String phone = cursor.getString(2);
System.out.println("name==>"+name+" phone==>"+phone);
}
}
}
}
MyOpenHelper:
package com.demo.siyoushujuku;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper( Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public MyOpenHelper(Context context) {
super(context, "Account.db", null, 1);
}
/**
* 数据库的名字
*
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20),money varchar(20))");
db.execSQL("insert into info(name,money) values(?,?)", new String[]{"张三","5000"});
db.execSQL("insert into info(name,money) values(?,?)", new String[]{"李四","3000"});
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.siyoushujuku">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--内容提供者-->
<provider
android:authorities="com.provider"
android:name=".AccountProvider"
android:exported="true"
>
</provider>
</application>
</manifest>
B.第一个项目:DQDYGApplication
结构图如下:
MainActivity:
package com.demo.dqdygapplication;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
/**
* 内容提供者吧数据进行封装 然后提供出来 其他应用都是
* 通过内容解析者来访问
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyOpenHelper myOpenHelper = new MyOpenHelper(getApplicationContext());
//需求 读取第一个应用私有数据库
/**
* path路径 accound.db
*
* factory:游标工厂
*
* flages:访问模式
*
*/
// SQLiteDatabase db = myOpenHelper.getReadableDatabase();
SQLiteDatabase db = SQLiteDatabase.openDatabase(
"/data/data/com.demo.dqdygapplication/databases/Account.db",
null, SQLiteDatabase.OPEN_READWRITE
);
Cursor cursor = db.query("info", null,
null, null,
null, null,
null
);
//由于数据库由第一个内容提供者暴露出来了 所以我们来解析即可
//1.拿到内容的解析者
Uri uri = Uri.parse("content://com.provider/query"); //路径和你定义的路径一样
Cursor cursor1 = getContentResolver().query(uri, null, null,
null, null
);
if (cursor1 != null && cursor1.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(1);
String phone = cursor.getString(2);
System.out.println("第二个应用:name==>" + name + " phone==>" + phone);
}
}
}
//增加
public void click1(View view) {
Uri uri = Uri.parse("content://com.provider/insert"); //路径和你定义的路径一样
ContentValues values = new ContentValues();
//key 对应表的字段 value的对应值
values.put("name","zhaoliu");
values.put("money",11111);
Uri insert = getContentResolver().insert(uri, values);
System.out.println("insert==>"+insert);
}
//删除
public void click2(View view) {
Uri uri = Uri.parse("content://com.provider/delete"); //路径和你定义的路径一样
int delete = getContentResolver().delete(uri, "name=?", new String[]{"zhaoliu"});
Toast.makeText(getApplicationContext(),"删除了"+delete+"行",Toast.LENGTH_LONG).show();
}
//修改
public void click3(View view) {
Uri uri = Uri.parse("content://com.provider/update"); //路径和你定义的路径一样
ContentValues values = new ContentValues();
values.put("money",0.1111);
int update = getContentResolver().update(uri, values,"name=?", new String[]{"zhaoliu"});
Toast.makeText(getApplicationContext(),"更新了"+update+"行",Toast.LENGTH_LONG).show();
}
//查找
public void click4(View view) {
//1.拿到内容的解析者
Uri uri = Uri.parse("content://com.provider/query"); //路径和你定义的路径一样
Cursor cursor1 = getContentResolver().query(uri, null, null,
null, null
);
if (cursor1 != null && cursor1.getCount() > 0) {
while (cursor1.moveToNext()) {
String name = cursor1.getString(1);
String phone = cursor1.getString(2);
System.out.println("第二个应用:name==>" + name + " phone==>" + phone);
}
}
}
}
MyOpenHelper:
package com.demo.dqdygapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public MyOpenHelper(Context context) {
super(context, "Account.db", null, 1);
}
/**
* 数据库的名字
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20),money varchar(20))");
db.execSQL("insert into info(name,money) values(?,?)", new String[]{"张三","5000"});
db.execSQL("insert into info(name,money) values(?,?)", new String[]{"李四","3000"});
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:onClick="click1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
/>
<Button
android:onClick="click2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete"
/>
<Button
android:onClick="click3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update"
/>
<Button
android:onClick="click4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="find"
/>
</LinearLayout>