1.简单示例:通过ContentProvider暴露数据库,然后读取数据。

2.先加上一个工具类,用来使用copy assets下面的db文件代码如下:

public class MyDBOpenHelper extends SQLiteOpenHelper{

    private static final String TAG = "MyDBOpenHelper";
  /*** 这里是是data/data/包名 /databases/ **/
private static String DB_PATH = "/data/data/com.example.mycontentproviderleader/databases/";
private static String DB_NAME = "song.db"; private SQLiteDatabase myDataBase;
private final Context myContext; public void SetFilePath(String path){
DB_PATH = path;
}
public MyDBOpenHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
// TODO Auto-generated constructor stub
} public void createDataBase() throws IOException{
boolean dbExist = checkDataBase(); if(dbExist){ }else{
this.getReadableDatabase(); try {
copyDataBase(); } catch (IOException e) {
throw new Error("Error copying database");
}
}
} private boolean checkDataBase(){ SQLiteDatabase checkDB = null; try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){ checkDB.close();
return true;
}
return false;
//return checkDB != null ? true : false;
} private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName); //transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
} public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} @Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
} @Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.d(TAG, "onCreate: ***********");
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub } }

  

3.uri匹配器

  UriMatcher uri匹配器

  初始匹配器:UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

  添加uri:

  matcher.addURI(authority, "TableSong", 1);

  matcher.addURI(authority, "TableSongSinger", 2);

  matcher.addURI(authority,"TableSong/#",3);

  后面的1,2,3为标识ID,TbaleSong可以指查询表全部数据,TableSong/#可以指查询特定的数据

switch (math) {
case 1:
cursor = db.rawQuery("select * from TableSong where Words=?",new Sreing[]{""+4} ); break;
case 2 cursor = db.rawQuery("select * from TableSong where Words=?",new Sreing[]{""+2} ); break;
case 3:
long id= ContentUris.parseId(uri);
cursor = db.rawQuery("select * from TableSong where SongIndex =?",new String[]{""+id} );
}

  


4.编写ContentProvider类

/****这里只实现了个查询功能,简单的示例 ,插入,删除等没实现********/
public class MyProvider extends ContentProvider { private SQLiteDatabase db = null;
/*** 写入你的包名*/
private static final String authority = "com.example.mycontentproviderleader"; private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); static {
/****TabelSong,TabslSongSinger 是2张不同的数据表***/
matcher.addURI(authority, "TableSong", 1);
matcher.addURI(authority, "TableSongSinger", 2);
matcher.addURI(authority,"TableSong/#",3); } /*** 创建app数据库 ,我这里是从assets 下copy的*/
@Override
public boolean onCreate() { MyDBOpenHelper myDBOpenHelper=new MyDBOpenHelper(getContext());
try {
myDBOpenHelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
db = myDBOpenHelper.getReadableDatabase();
return true;
} @Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
int math = matcher.match(uri);
Cursor cursor = null;
switch (math) {
case 1:
cursor = db.rawQuery("select * from TableSong where Words=?" ,new String[]{"3"});
//cursor = db.query("TableSong", projection, selection, selectionArgs, null, null, sortOrder);
break;
case 2: cursor = db.rawQuery("select * from TableSong where Words=?",new String[]{"6"} ); break;
case 3:
long id= ContentUris.parseId(uri);
cursor = db.rawQuery("select * from TableSong where SongIndex =?",new String[]{""+id} ); default:
break;
}
return cursor;
} @Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
} @Override
public Uri insert(Uri uri, ContentValues values) {
int code = matcher.match(uri);
switch (code) {
case 1:
db.insert("info", null, values);
break; default:
break;
}
return null;
} @Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
} @Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
} }

  

5. 编写contentProvider类后要在xml里面配置:
/***这里是通过一个demo实现了暴露,获取数据,如果在另一个程序获取数据需要加上 权限  android:permission="com.example.mycontentproviderleader.permission"*******/

<!-- android:exported 是否对外开放 -->
<provider android:name="com.example.mycontentproviderleader.MyProvider"
android:authorities="com.example.mycontentproviderleader"
android:exported="true"
android:multiprocess="true"
android:permission="com.example.mycontentproviderleader.permission"/>

  

6.然后在Main里面通过contentResolver ,uri 获取Cursor就行了。

   ContentResolver contentResolver;
Uri uri;
contentResolver = getContentResolver();
uri = Uri.parse("content://com.example.mycontentproviderleader/TableSong");
Cursor cursor = contentResolver.query(uri, null, null, null, null);
while (cursor.moveToNext()){
String SongName=cursor.getString(cursor.getColumnIndex("SongName")); Log.d(TAG, "select:歌曲名称:"+SongName);
}

  

7: code

链接: https://pan.baidu.com/s/1c2aViBQ 密码: 8qtw

  


ContentProvider 的使用的更多相关文章

  1. Android之ContentProvider数据存储

    一.ContentProvider保存数据介绍 一个程序可以通过实现一个ContentProvider的抽象接口将自己的数据完全暴露出去,而且ContentProvider是以类似数据库中表的方式将数 ...

  2. Xamarin.Android之ContentProvider

    一.前言 掌握了如何使用SQLiteOpenHelper之后,我们就可以进行下一步的学习.本章我们将会学习如何使用ContentProvider来将数据库方面的操作封装起来,同时它还可以供其他应用访问 ...

  3. ContentProvider域名替换小工具

    开发项目域名想怎么换就怎么换,就是这么任性! 这是一个很有意思的小工具! 这是一个方便开发人员和测试人员的小工具!! 吐槽: 一直在做Android开发,一直总有一个问题存在:做自己公司的apk开发时 ...

  4. Android开发学习—— ContentProvider内容提供者

    * 应用的数据库是不允许其他应用访问的* 内容提供者的作用就是让别的应用访问到你的数据库.把私有数据暴露给其他应用,通常,是把私有数据库的数据暴露给其他应用. Uri:包含一个具有一定格式的字符串的对 ...

  5. 简单的学习心得:网易云课堂Android开发第六章SQLite与ContentProvider

    一.SQLite 1.基本操作: (1)创建数据库:在SQLiteOpenHelper的子类构造器中创建. (2)创建表:在SQLiteOpenHelper的子类onCreate方法中,调用execS ...

  6. ContentProvider中央档案馆,以及获取联系人电话的示例

    Android官方文档介绍的数据存储方式共有五种,sqlite,SharedPreferences,网络存储,外储存储,文件存储,但是这些数据都无法进行共享,那么我们就引入了今天的主角:Content ...

  7. Android基础 : Android ContentProvider

    Android 应用程序通过ContentProvider实现方式统一的数据共享功能. 外界的程序通过ContentResolver接口可以访问ContentProvider提供的数据,在Activi ...

  8. 安卓初級教程(3):ContentProvider的運用原理

    package com.example.android.provider; import java.util.ArrayList; import java.util.HashMap; import j ...

  9. Android探索之ContentProvider熟悉而又陌生的组件

    前言: 总结这篇文章之前我们先来回顾一下Android Sqlite数据库,参考文章:http://www.cnblogs.com/whoislcj/p/5506294.html,Android程序内 ...

  10. 四大组件之ContentProvider

    前言 ContentProvider作为Android的四大组件之一,是属于需要掌握的基础知识,可能在我们的应用中,对于Activity和Service这两个组件用的很常见,了解的也很多,但是对Con ...

随机推荐

  1. spring实现helloWord

    第一步:添加架包 第二步:写一个简单的实列 package com.java.test; /** * @author nidegui * @create 2019-06-22 10:58 */ pub ...

  2. PAT_A1134#Vertex Cover

    Source: PAT A1134 Vertex Cover (25 分) Description: A vertex cover of a graph is a set of vertices su ...

  3. es 存入失败错误

    {, 'error': {'type': 'illegal_argument_exception', 'reason': 'Rejecting mapping update to [bd_date] ...

  4. esp32(M5STACK) ARDUINO开发环境搭建(ubuntu)

    首先去官网下载arduino https://www.arduino.cc/en/main/software         由于国产链接下载慢的缘故,所以可以采用百度网盘的方式进行下载,具体下载方法 ...

  5. 排序算法总结(C++)

    算法复杂度 稳定:如果a原本在b前面,而a=b,排序之后a仍然在b的前面. 不稳定:如果a原本在b的前面,而a=b,排序之后 a 可能会出现在 b 的后面. 时间复杂度:对排序数据的总的操作次数.反映 ...

  6. Java异常以及继承的一些问题

    Java异常以及继承的一些问题 http://blog.csdn.net/hguisu/article/details/6155636 https://www.cnblogs.com/skywang1 ...

  7. PAT 1072. Gas Station

    A gas station has to be built at such a location that the minimum distance between the station and a ...

  8. 【ZOJ 4070】Function and Function

    [链接] 我是链接,点我呀:) [题意] [题解] 递归一会. 会发现最后肯定是0,1一直循环. 开始循环之后就直接返回结果就好. [代码] #include <bits/stdc++.h> ...

  9. (28)SpringBoot启动时的Banner设置【从零开始学Spring Boot】

    对于使用过Spring Boot的开发者来说,程序启动的时候输出的由字符组成的Spring符号并不陌生.这个是Spring Boot为自己设计的Banner: 1.    .   ____       ...

  10. elasticsearch 权威指南入门阅读笔记(一)

    相关文档 esapi:https://es.xiaoleilu.com/010_Intro/10_Installing_ES.html     https://esdoc.bbossgroups.co ...