ContentProvider 的使用

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

  


今天多一点积累,明天少一分烦恼
原文地址:https://www.cnblogs.com/galibujianbusana/p/7457212.html