android contentprovider内容提供者

contentprovider内容提供者:让其他app可以访问私有数据库(文件)

1.AndroidManifest.xml

配置provider

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dbtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
    <!--android:name="com.example.dbtest.PersonContentProvider" 必须为内容提供者类的路径 不然会报notfoundclass--> <provider android:name="com.example.dbtest.PersonContentProvider" android:authorities="com.example.dbtest.provider.personprovider" android:exported="true"></provider> <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> </application> </manifest>

2.PersonContentProvider

package com.example.dbtest;

import com.example.dbtest.dbHelper.DbOpenHelper;

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 PersonContentProvider extends ContentProvider {

    private DbOpenHelper helper;
    //定义一个uri的匹配器用于匹配uri 如果路径不满足条件 返回-1
    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    
    private static final int INSERT = 1;
    private static final int DELETE = 2;
    private static final int UPDATE = 3;
    private static final int QUERY = 4;
    
    static{
        matcher.addURI("com.example.dbtest.provider.personprovider", "insert", INSERT);
        matcher.addURI("com.example.dbtest.provider.personprovider", "delete", DELETE);
        matcher.addURI("com.example.dbtest.provider.personprovider", "update", UPDATE);
        matcher.addURI("com.example.dbtest.provider.personprovider", "query", QUERY);
    }
    
    //content://com.itheima.db.personprovider/insert 添加操作
    //content://com.itheima.db.personprovider/delete 删除操作
    //content://com.itheima.db.personprovider/update 更新操作
    //content://com.itheima.db.personprovider/query  查询操作
    
    @Override
    public boolean onCreate() {
        helper = new DbOpenHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        if(matcher.match(uri)==QUERY)
        {
            SQLiteDatabase db = helper.getWritableDatabase();
            Cursor cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
            //注意  使用contentprovider时  不要将数据关闭掉   不然拿不到数据
            //db.close(); 不要关闭
            return cursor;
        }
        else
        {
            throw new IllegalArgumentException("路径不配对,不能执行查询操作");
        }
    }

    @Override
    public String getType(Uri uri) {
        
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if(matcher.match(uri)==INSERT)
        {
            SQLiteDatabase db = helper.getWritableDatabase();
            db.insert("person",null,values);
        }
        else
        {
            throw new IllegalArgumentException("路径不配对,不能执行插入操作");
        }
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        if(matcher.match(uri)==DELETE)
        {
            SQLiteDatabase db = helper.getWritableDatabase();
            db.delete("person", selection, selectionArgs);
        }
        else
        {
            throw new IllegalArgumentException("路径不配对,不能执行删除操作");
        }
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        if(matcher.match(uri)==UPDATE)
        {
            SQLiteDatabase db = helper.getWritableDatabase();
            db.update("person", values, selection, selectionArgs);
        }
        else
        {
            throw new IllegalArgumentException("路径不配对,不能执行修改操作");
        }
        return 0;
    }


}

3.其他app调用内容提供者

package com.example.getcontentprovider;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void query(View view)
    {
        System.out.println("start query...............");
        ContentResolver resolver = getContentResolver();
        Uri uri = Uri.parse("content://com.example.dbtest.provider.personprovider/query");
        Cursor cursor = resolver.query(uri, null, null, null, null);
        
        StringBuffer sb = new StringBuffer();
        while(cursor.moveToNext())
        {
            System.out.println("name:"+cursor.getString(cursor.getColumnIndex("name")));
            sb.append("name:"+cursor.getString(cursor.getColumnIndex("name"))+"
");
            
        }
        System.out.println("end query..............");
        
        Toast.makeText(this, sb.toString(),0).show();
        
    }
    
    public void delete(View view)
    {
        ContentResolver resolver = getContentResolver();
        Uri uri = Uri.parse("content://com.example.dbtest.provider.personprovider/delete");
        resolver.delete(uri, "id=?", new String[]{"1"});
        
        Toast.makeText(this, "删除成功",0).show();
        
    }
    
    public void update(View view)
    {
        ContentResolver resolver = getContentResolver();
        Uri uri = Uri.parse("content://com.example.dbtest.provider.personprovider/update");
        ContentValues values = new ContentValues();
        values.put("name", "张三");
        resolver.update(uri, values, "id=?", new String[]{"1"});
        
        Toast.makeText(this, "修改成功",0).show();
        
    }
    
    public void insert(View view)
    {
        
        ContentResolver resolver = getContentResolver();
        Uri uri = Uri.parse("content://com.example.dbtest.provider.personprovider/insert");
        ContentValues values = new ContentValues();
        values.put("name", "李四");
        resolver.insert(uri, values);
        
        Toast.makeText(this, "修改成功",0).show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
原文地址:https://www.cnblogs.com/zoro-zero/p/3947374.html