欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android进阶——ContentProvider&ContentResolver

程序员文章站 2024-02-10 22:28:46
...

学习使用ContentProvider

前言:我们为什么要学习ContentProvider与ContentResolver?

当我们想要跨进程共享多媒体数据时,就可以通过ContentProvider将多媒体数据共享出来,其它APP就可以通过ContentResolver来获取所需数据。


(一)ContentProvider与ContentResolver的含义

ContentProvider概念:

ContentProvider是Android的四大组件之一;
ContentProvider是一种数据包装器,提供统一的接口对数据进行操作;
ContentProvider主要用于不同程序或者不同应用之间的数据共享。

ContentResolver的概念:

ContentResolver是数据调用者,ContentProvider将数据发布出来后,通过ContentResolver对象结合Uri进行调用;
通过 ContentResolver可以调用ContentProvider的增、删、改、查操作。


(二)Uri和UriMatcher

Uri

Uri是一种资源标识符,代表要操作数据的地址,在调用ContentProvider之前,一定要确定Uri。

参考样式:

content://com.example.asus.studentdemo.provider
UriMatcher

通过UriMatcher对象的addURI方法来定义Uri规则,也就是验证口令,其一是验证authority(Uri资源存放位置),其二验证path(Uri中的资源路径)。


(三)创建自定义ContentProvider的步骤

  1. 使用SQLite技术,创建好数据库和数据表;
  2. 新建类继承ContentProvider;
  3. 创建UriMatcher,定义Uri规则;
  4. 重写6个抽象方法(onCreate、insert、delete、getType、update、query);
  5. 在AndroidManifest中注册Provider;
  6. ContentResolver 对ContentProvider共享的数据进行增删改查。

步骤图:

Android进阶——ContentProvider&ContentResolver

这里我们一定要记得在资源提供者的AndroidManifest中注册provider

<provider
            android:enabled="true"
            android:exported="true"
            android:authorities="com.example.asus.studentdemo.provider"
            android:name=".MyProvider"/>

(四)ContentProvider的实例

内容提供方创建类继承ContentProvider:

public class MyProvider extends ContentProvider {

    private String TAG = "StudentResolver";

    private SQLiteDatabase database;


//    private  static  final int STUDENT=0;
//    private  static final  int STUDENT_ITEM=1;
//    private  static  final int TEACHER=2;
//    private  static final  int TEACHER_ITEM=3;
//    private  static final  String AUTHORITY="com.example.asus.studentdemo.provider";
//    private static UriMatcher uriMatcher;
//    static {
//        uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
//        uriMatcher.addURI(AUTHORITY,"student",STUDENT);
//        uriMatcher.addURI(AUTHORITY,"student/#",STUDENT_ITEM);
//        uriMatcher.addURI(AUTHORITY,"teacher",TEACHER);
//        uriMatcher.addURI(AUTHORITY,"teacher/#",TEACHER_ITEM);
//    }


    @Override
    public boolean onCreate() {
        Log.e(TAG, "onCreate..........");
        return false;
    }


    //查找
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        Log.e(TAG, "query..........");
        DBHelper dbHelper = new DBHelper(getContext(), "SQLName", null, 1);
        database = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        cursor = database.query("student", projection, selection, selectionArgs, null, null, sortOrder);
        return cursor;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        Log.e(TAG, "getType..........");
        return null;
    }


    //增加
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {

//        int m=uriMatcher.match(uri);
        Log.e(TAG, "insert..........");
        DBHelper dbHelper = new DBHelper(getContext(), "SQLName", null, 1);
        SQLiteDatabase database = dbHelper.getWritableDatabase();
//        ContentValues v=new ContentValues();
//        v.put("name","xiaomeinv");
        database.insert("student", null, values);
        return null;
    }

    //删除
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.e(TAG, "delete..........");
        DBHelper dbHelper = new DBHelper(getContext(), "SQLName", null, 1);
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.delete("student",selection,selectionArgs);
        return 100;
    }


    //修改
    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        Log.e(TAG, "update..........");
        DBHelper dbHelper = new DBHelper(getContext(), "SQLName", null, 1);
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        int updateRows=0;
        updateRows=database.update("student",values,selection,selectionArgs);
        return updateRows;
    }
}

内容提供方注册provider

 <provider
            android:enabled="true"
            android:exported="true"
            android:authorities="com.example.asus.studentdemo.provider"
            android:name=".MyProvider"/>

内容接收方对分享数据进行增删改查

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button ceshiBtn;
    private Button insertBtn;
    private Button deleteBtn;
    private Button updateBtn;
    private Button queryBtn;

    private EditText insertET;
    private EditText deleteET;
    private EditText updateBeforeET;
    private EditText updateAfterET;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bindID();
    }

    private void bindID() {
        ceshiBtn = findViewById(R.id.ceshi_btn);
        insertBtn = findViewById(R.id.insert_btn);
        deleteBtn = findViewById(R.id.delete_btn);
        updateBtn = findViewById(R.id.update_btn);
        queryBtn = findViewById(R.id.query_btn);

        insertET = findViewById(R.id.insert_et);
        deleteET = findViewById(R.id.delete_et);
        updateBeforeET = findViewById(R.id.updatebefore__et);
        updateAfterET = findViewById(R.id.updateafter_et);

        ceshiBtn.setOnClickListener(this);
        insertBtn.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);
        updateBtn.setOnClickListener(this);
        queryBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //测试按钮
            case R.id.ceshi_btn:
                Uri uri = Uri.parse("content://com.example.asus.studentdemo.provider");
                ContentResolver resolver = getContentResolver();
                resolver.delete(uri, null, null);
                break;


                //插入按钮
            case R.id.insert_btn:
                String name=insertET.getText().toString();
                Uri uri1 = Uri.parse("content://com.example.asus.studentdemo.provider");
                ContentResolver resolver1=getContentResolver();
                ContentValues values=new ContentValues();
                values.put("name",name);
                resolver1.insert(uri1,values);
                break;


                //删除按钮
            case R.id.delete_btn:
                Uri uri2=Uri.parse("content://com.example.asus.studentdemo.provider");
                ContentResolver resolver2=getContentResolver();
                resolver2.delete(uri2,"name=?",new String[]{deleteET.getText().toString()});
                break;


                //修改按钮
            case R.id.update_btn:
                String aftername=updateAfterET.getText().toString();
                Uri uri3=Uri.parse("content://com.example.asus.studentdemo.provider");
                ContentResolver resolver3=getContentResolver();
                ContentValues values3=new ContentValues();
                values3.put("name",aftername);
                resolver3.update(uri3,values3,"name=?",new String[]{updateBeforeET.getText().toString()});
                break;


                //查找按钮
            case R.id.query_btn:
                Uri uri4=Uri.parse("content://com.example.asus.studentdemo.provider/student");
                Cursor cursor=getContentResolver().query(uri4,null,null,null,null);
                if (cursor!=null){
                    while (cursor.moveToNext()){
                        String sname=cursor.getString(cursor.getColumnIndex("name"));
                        Log.e( "onClick: ",sname );
                    }
                    cursor.close();
                }
                break;
        }

    }
}