android ContentProvider访问SQLite数据库Demo

来源:互联网 发布:软件的架构设计 编辑:程序博客网 时间:2024/05/22 12:13
/**
 * 内容提供者,暴露自己的私有数据给别人,控制别人访问时的权限
 * 想将数据提供给不同的应用时,需要使用ContentResolve
 * 继承ContentProvider
 * 重写这些方法
 * onCreate()
 * query(URI,String[],String,String[],String)
 * insert(Uri,ContentValues)
 * update(Uri,ContentVaslues,String,String[])
 * delate(Uri,String,String[]);
 * getType(Uri)
 * ContentValues放的是一个Map
 */
创建一个类继承ContentProvider
需要在AndroidMainfest.xml声明provider
<provider
            android:exported="true"
            android:authorities="com.example.provider"
            android:name=".MyProvider">
        </provider>
        <!--要想访问这个MyProvider 必须通过authorities来访问用来给别人访问
        exported="true"
        -->

以下代码实例:
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void insert(View view){
        ContentResolver contentResolver=getContentResolver();
        Uri uri=Uri.parse("content://com.example.provider/insert");
        ContentValues values=new ContentValues();
        values.put("name","lisasasa");
        values.put("phone","12345678954");
        Uri insertUri=contentResolver.insert(uri,values);
    }
    public void delete(View view){
        ContentResolver contentResolver=getContentResolver();
        Uri uri=Uri.parse("content://com.example.provider/delete");
        ContentValues values=new ContentValues();
        String where ="name=?";
        String[] selectArgs={"lisasasa"};
        int result=contentResolver.delete(uri,where,selectArgs);
    }
    public void update(View view){
        //拿到内容解析者
        ContentResolver contentResolver=getContentResolver();
        Uri uri=Uri.parse("content://com.example.provider/update");
        ContentValues values=new ContentValues();
        values.put("phone","110");
        String where="name = ?";
        String[] selectArgs={"zhangsan"};
        int result=contentResolver.update(uri,values,where,selectArgs);
    }
    /**
     * @param view
     * 查询全部
     */
    public void query(View view){
        ContentResolver contentResolver=getContentResolver();
        Uri uri=Uri.parse("content://com.example.provider/query");
        Cursor cursor=contentResolver.query(uri,null,null,null,null);
        while (cursor.moveToNext()) {
            String name=cursor.getString(cursor.getColumnIndex("name"));
            String phone=cursor.getString(cursor.getColumnIndex("phone"));
            System.out.println("------------------------>"+name);
            System.out.println("------------------------>"+phone);
        }

    }
}



public class MyProvider extends ContentProvider {

    private SQLiteOpenHelper myOpenHelper;
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int QUERY_SUCCESS = 0;
    private static final int INSERT_MATCH = 1;
    private static final int UPDATE_MATCH = 2;
    private static final int DELETE_MATCH = 3;

    static {
        //给当前的URI匹配器添加一个匹配规则
        //参数介绍:authorities
        // path   限制操作,例如下面的只能做查询
        //code     返回码
        uriMatcher.addURI("com.example.provider", "query", QUERY_SUCCESS);
        uriMatcher.addURI("com.example.provider", "insert", INSERT_MATCH);
        uriMatcher.addURI("com.example.provider", "update", UPDATE_MATCH);
        uriMatcher.addURI("com.example.provider", "delete", DELETE_MATCH);
    }

    @Override
    public boolean onCreate() {
        myOpenHelper = new MyOpenHelper(getContext());

        return false;
    }

    /**
     * @param uri
     * @param projection
     * @param selection
     * @param selectionArgs
     * @param sortOrder
     * @return 不能关,关了cursor就没用了
     * Uri包含了authorities用来判断访问了哪一个provider
     * Uri除了authorities外还有其他内容通过URIMatcher解析Uri
     */
    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        //当前操作是如果匹配上返回一个QUERY_SUCCESS,否则返回UriMatcher.NO_MATCH
        int code = uriMatcher.match(uri);
        if (code == QUERY_SUCCESS) {
            SQLiteDatabase database = myOpenHelper.getReadableDatabase();
            Cursor cursor = database.query("info", projection, selection, selectionArgs, null, null, sortOrder);
            return cursor;
        } else {
            throw new IllegalStateException("非法操作");
//            return null; 抛异常或者返回空
        }
    }

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

    /**
     * @param uri
     * @param values
     * @return
     */
    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        int code = uriMatcher.match(uri);
        if (code == INSERT_MATCH) {
            SQLiteDatabase database = myOpenHelper.getReadableDatabase();
            long rowId = database.insert("info", null, values);
            database.close();
            return Uri.parse(String.valueOf(rowId));
        } else {
            throw new IllegalStateException("非法操作");
//            return null; 抛异常或者返回空
        }
    }

    /**
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int code = uriMatcher.match(uri);
        if (code == DELETE_MATCH) {
            SQLiteDatabase database = myOpenHelper.getReadableDatabase();
            int delete = database.delete("info", selection, selectionArgs);
            return delete;
        } else {
            throw new IllegalStateException("非法操作");
//            return null; 抛异常或者返回空
        }
    }

    /**
     * @param uri
     * @param values
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int code = uriMatcher.match(uri);
        if (code == UPDATE_MATCH) {
            SQLiteDatabase database = myOpenHelper.getReadableDatabase();
            int update = database.update("info", values, selection, selectionArgs);
            database.close();
            return update;
        } else {
            throw new IllegalStateException("非法操作");
//            return null; 抛异常或者返回空
        }
    }
}



//android下的数据库SQLITE
public class MyOpenHelper extends SQLiteOpenHelper {

    /**
     * @param context
     *   数据库文件名字 在内存中创建一个数据库,临时用一下则可以传null
     *    传null
     *  数据库版本号从1开始
     */
    public MyOpenHelper(Context context) {
        super(context, "itheima.db", null, 1);
    }

    /**
     * @param db
     * s数据库第一次创建时调用
     * 这里进行表结构创建,数据初始化
     * _id sqlite种的id这一列字段名一般为_id
     * sqlite数据库存的都是字符串
     * 表的修改都在这里操作,
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20),phone varchar(20))");
        db.execSQL("insert into info ('name','phone') values ('zhangsan','1569863')");
        db.execSQL("insert into info ('name','phone') values ('lisi','1597534682')");
    }

    /**
     * @param db
     * @param oldVersion
     * @param newVersion
     * CURD
     * 表的修改都在这里操作,数据库版本越来越高
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("alter table info add age integer");//增加表字段
    }

    /**
     * @param db
     * @param oldVersion
     * @param newVersion
     *执行数据库版本降级 数据库版本越来越低
     */
    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//        super.onDowngrade(db, oldVersion, newVersion);    //不注释掉会抛异常
    }
}



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.zhongtao.day10.MainActivity">

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:text="Hello World!" />
    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="insert"
        android:text="insert"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/query"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="query"
        android:text="query"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="delete"
        android:text="delete"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="update"
        android:text="update"
        android:textAllCaps="false"
        />
</LinearLayout>

0 0