自定义provider

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hipeak.demo0804">

    <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/Theme.Demo0804">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <provider
            android:authorities="com.hipeak.demo0804.stuprovider"
            android:name=".StuProvider"
            android:exported="true"
            android:enabled="true"/>
    </application>

</manifest>

MainActivity

package com.hipeak.demo0804;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class StuProvider extends ContentProvider {
    private SchoolDBHelper helper;
    /**
     * 匹配URi的容器
     *  构造的code:匹配不上的时候,code是多少,默认是NO_MATCH -1
     */
    private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
    private static final int CODE_STU=1;
    private static final int CODE_STU_ID=2;
    static{
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu",CODE_STU);
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu/#",CODE_STU_ID);
    }

    //当应用启动的时候创建StuProvider对象,当创建对象的时候onCreate()
    //初始化helper
//    private
    @Override
    public boolean onCreate() {
        Log.d("", "===onCteate");
        helper=new SchoolDBHelper(getContext(),1);
        return false;
    }

    /**
     *
     * @param uri  一个资源的唯一标识
     * @param projection 多个字段
     * @param selection where条件 如:id=?and name=?
     * @param selectionArgs  where条件需要的值
     * @param sortOrder 排序规则
     * @return
     *
     * content://com.hipeak.demo0804.stuprovider/stu    不根据id查询
     * content://com.hipeak.demo0804.stuprovider/stu/1  根据id查询
     */
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri,
                        @Nullable String[] projection,
                        @Nullable String selection,
                        @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {
        SQLiteDatabase db = helper.getReadableDatabase();
        int code = matcher.match(uri);
        switch(code){
            case CODE_STU:
                return db.query("stu",projection,selection,selectionArgs,null,null,sortOrder);
            case CODE_STU_ID:
                //TODO uri中的id获取
                long id=ContentUris.parseId(uri);//uri中的id
                return db.query("stu",projection,"_id=?",new String[]{id+""},null,null,sortOrder);
            default:
                Log.e("","Uri不符合规则");
                throw new RuntimeException("Uri不符合规则");
        }
    }


    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    //* * content://com.hipeak.demo0804.stuprovider/stu    不根据插入
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code =matcher.match(uri);
        if(code==CODE_STU){
            long id = db.insert("stu", null, values);
            Log.d("","id==="+id);
            db.close();
            return ContentUris.withAppendedId(uri,id);
        }else{
            Log.e("","Uri不符合规则");
            db.close();
            throw new RuntimeException("Uri不符合规则");
        }

    }

    /**
     *  content://com.hipeak.demo0804.stuprovider/stu    不根据id删除
     *  content://com.hipeak.demo0804.stuprovider/stu/1  根据id删除
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code=matcher.match(uri);
        int count=0;
        switch(code){
            case CODE_STU:
                count = db.delete("stu", selection, selectionArgs);//删掉了几行
                db.close();
                break;
            case CODE_STU_ID:
                long id=ContentUris.parseId(uri);
                count=db.delete("stu","_id=?",new String[]{id+""});
                db.close();
                break;
            default:
                throw new RuntimeException("Uri不符合规则");
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }


}

SchoolDBHelper

package com.hipeak.demo0804;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class SchoolDBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME="school.db";

    public SchoolDBHelper(@Nullable Context context, int version) {
        super(context, DB_NAME, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //
        String sql="create table stu(" +
                "_id integer primary key autoincrement" +
                ",name text" +
                ",age integer );";

        sqLiteDatabase.execSQL(sql);

        String sql2="insert into stu(name,age) values('张三',21),('李四',21),('王五',26)" ;

        sqLiteDatabase.execSQL(sql2);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

StuProvider

package com.hipeak.demo0804;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class StuProvider extends ContentProvider {
    private SchoolDBHelper helper;
    /**
     * 匹配URi的容器
     *  构造的code:匹配不上的时候,code是多少,默认是NO_MATCH -1
     */
    private static UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
    private static final int CODE_STU=1;
    private static final int CODE_STU_ID=2;
    static{
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu",CODE_STU);
        matcher.addURI("com.hipeak.demo0804.stuprovider","/stu/#",CODE_STU_ID);
    }

    //当应用启动的时候创建StuProvider对象,当创建对象的时候onCreate()
    //初始化helper
//    private
    @Override
    public boolean onCreate() {
        Log.d("", "===onCteate");
        helper=new SchoolDBHelper(getContext(),1);
        return false;
    }

    /**
     *
     * @param uri  一个资源的唯一标识
     * @param projection 多个字段
     * @param selection where条件 如:id=?and name=?
     * @param selectionArgs  where条件需要的值
     * @param sortOrder 排序规则
     * @return
     *
     * content://com.hipeak.demo0804.stuprovider/stu    不根据id查询
     * content://com.hipeak.demo0804.stuprovider/stu/1  根据id查询
     */
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri,
                        @Nullable String[] projection,
                        @Nullable String selection,
                        @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {
        SQLiteDatabase db = helper.getReadableDatabase();
        int code = matcher.match(uri);
        switch(code){
            case CODE_STU:
                return db.query("stu",projection,selection,selectionArgs,null,null,sortOrder);
            case CODE_STU_ID:
                //TODO uri中的id获取
                long id=ContentUris.parseId(uri);//uri中的id
                return db.query("stu",projection,"_id=?",new String[]{id+""},null,null,sortOrder);
            default:
                Log.e("","Uri不符合规则");
                throw new RuntimeException("Uri不符合规则");
        }
    }


    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }
    //* * content://com.hipeak.demo0804.stuprovider/stu    不根据插入
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code =matcher.match(uri);
        if(code==CODE_STU){
            long id = db.insert("stu", null, values);
            Log.d("","id==="+id);
            db.close();
            return ContentUris.withAppendedId(uri,id);
        }else{
            Log.e("","Uri不符合规则");
            db.close();
            throw new RuntimeException("Uri不符合规则");
        }

    }

    /**
     *  content://com.hipeak.demo0804.stuprovider/stu    不根据id删除
     *  content://com.hipeak.demo0804.stuprovider/stu/1  根据id删除
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int code=matcher.match(uri);
        int count=0;
        switch(code){
            case CODE_STU:
                count = db.delete("stu", selection, selectionArgs);//删掉了几行
                db.close();
                break;
            case CODE_STU_ID:
                long id=ContentUris.parseId(uri);
                count=db.delete("stu","_id=?",new String[]{id+""});
                db.close();
                break;
            default:
                throw new RuntimeException("Uri不符合规则");
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }


}
  break;
            default:
                throw new RuntimeException("Uri不符合规则");
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        return 0;
    }


}

版权声明:本文为qq_45015014原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_45015014/article/details/127779206