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

ContentProvider&ContentResolver

程序员文章站 2024-02-09 16:50:16
...

一.ContentProvider是什么

1.ContentProvider是Android四大组件之一
2.ContentProvider是一种数据包装器,它提供统一的接口对数据进行操作,调用者不用关心数据到底是如何存储的
3.ContentProvider主要用于不同的应用程序间,不同进程间的数据共享

二.ContentResolver是什么

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

三.URI是什么,标准格式是什么

URI是什么

1.通用资源标识符简称Uri
2.Uri代表操作数据的地址,每个ContentProvider发布数据时都有一个唯一的地址

标准格式

content://com.android.contacts/contacts
content://:此部分是固定写法,用来表明这是一个Uri
com.android.contacts:此部分指定了要访问的资源的存放地址
contacts:此部分指定了要访问资源的路径

四.UriMatcher是什么

1.用于匹配Uri的Uri规则工具类
2.当调用者传递过来Uri时,我们需要对Uri进行解析,确定调用者需要执行哪个操作

五.如何使用ContentProvider

我写的是一个学生表,有id,name,age,下面通过这个例子来体现如何使用ContentProvider
1.使用SQLite技术,创建好数据库和数据表

package com.example.practiceapplication.sqlite;

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

/**
 * Created by lyj on 2018/6/21.
 */

public class StuSQLiteHelper extends SQLiteOpenHelper{
    private String sql="create table stu(" +
            "id integer primary key autoincrement not null,"+
            "name text," +
            "age integer" +
            ")";
    public StuSQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(sql);

    }

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

    }
}

2.新建类继承ContentProvider
会报错,第四步是解决方法

package com.example.practiceapplication.sqlite;

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.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * Created by lyj on 2018/6/21.
 */

public class StudentProvider extends ContentProvider {

}

3.创建UriMatcher,定义Uri规则

private UriMatcher uriMatcher;
 {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI("content://com.example.practiceapplication.sqlite.StudentProvider", "stu", 1);
        uriMatcher.addURI("content://com.example.practiceapplication.sqlite.StudentProvider", "tea", 1);
    }

4.重写6个抽象方法

package com.example.practiceapplication.sqlite;

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.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * Created by lyj on 2018/6/21.
 */

public class StudentProvider extends ContentProvider {
    private SQLiteDatabase sqLiteDatabase;
    private StuSQLiteHelper stuSQLiteHelper;

    private UriMatcher uriMatcher;

    private Cursor cursor;

    @Override
    public boolean onCreate() {
        stuSQLiteHelper = new StuSQLiteHelper(getContext(), "stu_db", null, 1);

        return false;
    }

    {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI("content://com.example.practiceapplication.sqlite.StudentProvider", "stu", 1);
        uriMatcher.addURI("content://com.example.practiceapplication.sqlite.StudentProvider", "tea", 1);
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {

//        switch (uriMatcher.match(uri)) {
//            case 1:
                cursor = sqLiteDatabase.query("stu", null, null, null, null, null, null);
//
//                break;
//            case 2:
//                break;
//            default:
//                break;
//
//        }
        return cursor;
    }

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

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        sqLiteDatabase = stuSQLiteHelper.getWritableDatabase();

        long id = sqLiteDatabase.insert("stu", null, contentValues);
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {

        sqLiteDatabase = stuSQLiteHelper.getWritableDatabase();


        return sqLiteDatabase.delete("stu", s, strings);
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {

        sqLiteDatabase = stuSQLiteHelper.getWritableDatabase();

        return sqLiteDatabase.update("stu", contentValues, s, strings);
    }
}

5.在AndroidManifest中注册provider

 <provider
            android:name=".sqlite.StudentProvider"
            android:authorities="com.example.practiceapplication.sqlite.StudentProvider"
            android:exported="true" />

6.ContentResolver对ContentProvider共享的数据进行增删改查

package com.example.lyj.myapplication;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class ProviderActivity extends AppCompatActivity implements View.OnClickListener{
    private Uri uri;
    private ContentResolver contentResolver;

    private EditText stuAge_et, stuName_et;
    private ListView stu_lv;
    private SQLiteAdapter adapter;
    private Button add_button, search_button, update_button, delete_button;

    private List<SQLiteStu> sqLiteStuList=new ArrayList<>();

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

        stuAge_et = findViewById(R.id.stuAge_et);
        stuName_et = findViewById(R.id.stuName_et);

        add_button = findViewById(R.id.add_button);
        add_button.setOnClickListener(this);

        search_button = findViewById(R.id.search_button);
        search_button.setOnClickListener(this);

        update_button = findViewById(R.id.update_button);
        update_button.setOnClickListener(this);

        delete_button = findViewById(R.id.delete_button);
        delete_button.setOnClickListener(this);

        stu_lv=findViewById(R.id.stu_lv);

        uri=Uri.parse("content://com.example.practiceapplication.sqlite.StudentProvider");
        contentResolver=getContentResolver();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_button:
                sqLiteStuList.clear();

                Cursor cursor=contentResolver.query(uri,new String[]{"id","name","age"},null,null,null);

                cursor.moveToFirst();

                    do {
                        int id = cursor.getInt(cursor.getColumnIndex("id"));
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        String age = cursor.getString(cursor.getColumnIndex("age"));

                        SQLiteStu sqLiteStu = new SQLiteStu(id, name, age);
                        sqLiteStuList.add(sqLiteStu);
                        adapter = new SQLiteAdapter(this, sqLiteStuList);

                        stu_lv.setAdapter(adapter);

                    } while (cursor.moveToNext());


                break;
            case R.id.add_button:
                String age1= stuAge_et.getText().toString();
                String name1=stuName_et.getText().toString();

                ContentValues values=new ContentValues();
                values.put("name",name1);
                values.put("age",age1);

                contentResolver.insert(uri,values);
                break;
            case R.id.delete_button:
                String name2=stuName_et.getText().toString();
                String age2= stuAge_et.getText().toString();

                contentResolver.delete(uri,"name=? and age=?",new String[]{name2,age2});
                break;
            case R.id.update_button:
                String age3= stuAge_et.getText().toString();
                String name3=stuName_et.getText().toString();

                ContentValues contentValues=new ContentValues();
                contentValues.put("name","鹏鹏");
                contentValues.put("age","20");

                contentResolver.update(uri,contentValues,"name=? and age=?",new String[]{name3,age3});
                break;
            default:
                break;
        }
    }
}