ContentProvider讲解与实例应用

什么是ContentProvider

是Android的四大组件之一
主要用于不同的应用程序之间实现数据共享功能

什么是ContentResolver:

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

什么是Uri:

Uri(通用资源标识符 Universal Resource Identifer),代表数据操作的地址,每一个ContentProvider发布数据时都会有唯一的地址。
比如:content://(固定写法)+com.android.contacts(包名,可变)+/contacts(path路径)

创建自定义ContentProvider的步骤:

1.使用SQLite技术,创建好数据库和数据表
2.新建类继承ContentProvider
3.重写6个抽象方法
4.创建UriMatcher,定义Uri规则
5.在Manifest中注册provider
6.ContentResolver对ContentProvider中共享的数据进行增删改查操作

ContentProvider实例应用
实现效果:(两个app之间进行数据的增删改查)

1.增:

2.删:

3.改:

4.查:

ContentProvider讲解与实例应用_第1张图片
实现代码:

1.这次测试是在我已经创建了一个userdbdemo数据库和userdemo数据表的前提下做出的。

如果对数据库的知识不太了解,可以借鉴我写的两篇博客
[SQLite讲解与实例应用]
(https://blog.csdn.net/shaochen2015821426/article/details/79637550)
[使用LitePal插件操作数据库(增删改查)讲解与实例]
(https://blog.csdn.net/shaochen2015821426/article/details/79791232)

2.新建类继承ContentProvider,重写6个抽象方法,创建UriMatcher,定义Uri规则

//新建类继承ContentProvider
public class DatabaseProvider extends ContentProvider {

    private MyDBHelpter myDBHelpter;
    private static final String TAG = "DatabaseProvider";

    //添加整形常亮
    public static final int USER_DIR = 0;
    public static final int USER_ITEM = 1;
    //创建authority
    public static final String AUTHORITY = "com.example.administrator.databasetest.provider";
    //创建UriMatcher对象
    private static UriMatcher uriMatcher;

    //创建静态代码块
    static {
        //实例化UriMatcher对象
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //可以实现匹配URI的功能
        //参数1:authority 参数2:路径 参数3:自定义代码
        uriMatcher.addURI(AUTHORITY, "userdemo", USER_DIR);
        uriMatcher.addURI(AUTHORITY, "userdemo/#", USER_ITEM);
    }

    public DatabaseProvider() {
        Log.e(TAG, "DatabaseProvider: ");
    }

    //onCreate()方法
    @Override
    public boolean onCreate() {
        //实现创建MyDBHelpter对象
        myDBHelpter = new MyDBHelpter(getContext(), "userdbdemo", null, 1);
        return true;
    }

    //删除数据表数据
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        //创建SQLiteDatabase对象
        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        int deleteInt = 0;
        //匹配uri
        switch (uriMatcher.match(uri)) {
            case USER_DIR:
                //参数1:表名   参数2:约束删除列的名字   参数3:具体行的值
                deleteInt = db.delete("userdemo", selection, selectionArgs);
                break;
            case USER_ITEM:
                String deleteId = uri.getPathSegments().get(1);
                deleteInt = db.delete("userdemo", "id=?", new String[]{deleteId});
                break;
            default:
        }

        return deleteInt;
    }

    //插入数据
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        switch (uriMatcher.match(uri)) {
            case USER_DIR:
            case USER_ITEM:
                //参数1:表名  参数2:没有赋值的设为空   参数3:插入值
                long newUserId = db.insert("userdemo", null, values);
                break;
            default:
                break;
        }
        return null;
    }

    //查询数据
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        Cursor cursor = null;
        switch (uriMatcher.match(uri)) {
            case USER_DIR:
                //参数1:表名  其他参数可借鉴上面的介绍
                cursor = db.query("userdemo", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case USER_ITEM:
                String queryId = uri.getPathSegments().get(1);
                cursor = db.query("userdemo", projection, "id=?", new String[]{queryId}, null, null, sortOrder);
                break;
            default:
        }
        return cursor;

    }

    //更新数据
    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {

        SQLiteDatabase db = myDBHelpter.getWritableDatabase();
        int updateRow = 0;
        switch (uriMatcher.match(uri)) {
            case USER_DIR:
                updateRow = db.update("userdemo",values,selection,selectionArgs);
                break;
            case USER_ITEM:
                String updateId = uri.getPathSegments().get(1);
                updateRow = db.update("userdemo",values,"id=?",new String[]{updateId});

                break;
            default:
        }
        return updateRow;
    }

    @Override
    public String getType(Uri uri) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

#####3.在Manifest中注册provider

 

4.在另一个程序中启动:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{


    private Button insertBtn;
    private EditText editText;
    private Button deleteBtn;
    private  Button queryBtn;
    private Button updateBtn;

    private  String newId;

    private static final String TAG = "MainActivity";


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

        bangID();
    }

    private void bangID() {
        insertBtn = findViewById(R.id.main_insert_btn);
        editText = findViewById(R.id.main_et);
        deleteBtn = findViewById(R.id.main_delete_btn);
        queryBtn = findViewById(R.id.main_query_btn);
        updateBtn = findViewById(R.id.main_update_btn);


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


    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.main_insert_btn:
                String name = editText.getText().toString();
                //创建期待匹配的uri
                Uri uri1 = Uri.parse("content://com.example.administrator.databasetest.provider/userdemo");
                ContentValues values = new ContentValues();
                values.put("name",name);
                //获得ContentResolver对象,调用方法
                getContentResolver().insert(uri1,values);
                break;
            case R.id.main_delete_btn:
                String name1 = editText.getText().toString();
                Uri uri2 = Uri.parse("content://com.example.administrator.databasetest.provider/userdemo");
                getContentResolver().delete(uri2,"name=?",new String[]{name1});
                break;
            case R.id.main_query_btn:
                Uri uri = Uri.parse("content://com.example.administrator.databasetest.provider/userdemo");
                Cursor cursor = getContentResolver().query(uri,null,null,null,null);
                cursor.moveToFirst();
                do{
                    String name2 = cursor.getString(cursor.getColumnIndex("name"));
                    Log.e(TAG, "onClick: "+name2 );

                }while(cursor.moveToNext());
                cursor.close();
                break;
            case R.id.main_update_btn:
                String updateStr = editText.getText().toString();
                Uri uri3 =Uri.parse("content://com.example.administrator.databasetest.provider/userdemo");
                ContentValues values1 = new ContentValues();
                values1.put("name",updateStr);
                getContentResolver().update(uri3,values1,"name=?",new String[]{""});
                break;
            default:
        }

    }
}

over

你可能感兴趣的:(Android)