自定义内容提供者

   今天小编利用闲暇时间研究了一下的安卓的四大基本组件之一 ContentProvider(内容提供者),它主要用于在不同的应用程序之间实现数据共享的功能

    ContentProvider可以理解为一个安卓应用对外开放接口,只要符合它所定义的格式请求,就可以正常访问执行操作,其他安卓应用程序就尅通过

 ContentResolver对象与ContentProvider同名方法请求下执行。ContentProvider有很多对外可以以访问的方法,在ContentResolver中都有方法一

一对应。具体方法在下面讲解。

     创建自己的内容提供者首先要新建一个类继承抽象类ContentProvider并重写其方法,抽象方法如下:

除了onCreate()和getType()方法外,其他的均为CRUD操作,这些方法中,Uri参数为与ContentProvider匹配的请求Uri,剩下的参数和SQLite的CRUD操作,基本一致。

在ContentProvider中的CRUD操作中,都会传递一个Uri对象,通过这个对象来匹配对应的请求思考到如何确定uri执行那个操作呢,这时候就需要用到一个UriMatcher对象,它用来帮助内容提供者匹配uri,它所匹配的方法也很简单,就两个:


  • void addURI(String authority,String path,int code):添加一个Uri匹配项,authority为AndroidManifest.xml中注册的ContentProvider中的authority属性;path为一个路径,可以设置通配符,#表示任意数字,*表示任意字符串,code为自定义的一个Uri代码。
  • int match(Uri uri):匹配传递的Uri,返回addURI()传递的code参数。改方法小编没做大的了解。

   理论知识说到这,下面小编用内容提供者实现了简单的CRUD的操作,具体代码如下:

   ContentProvider:(提供数据)

ContentProvider:
public class MyLinkman extends ContentProvider {

    private DbHelper db;
    private SQLiteDatabase sqLiteDatabase;
    private UriMatcher uriMatcher;

    @Override
    public boolean onCreate() {
        Log.i("test","onCreate");
        db = new DbHelper(getContext(),"person.db",null,3);
        sqLiteDatabase = db.getReadableDatabase();
        //实例化uri的匹配器
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        //查询所有
        uriMatcher.addURI("com.example.contentprivoid.MyPerson","linkman",1);//添加匹配规则
        //查询单个
        uriMatcher.addURI("com.example.contentprivoid.MyPerson","linkman/#",2);//添加匹配规则
        return false;
    }
    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.i("test","query");
        //根据匹配器去匹配
        int type=uriMatcher.match(uri);
        switch (type){
            case 1://查询所有
                Log.i("test","查询所有");
                return  sqLiteDatabase.query(false,"person",projection,selection,selectionArgs,null,null,sortOrder,null);
            case 2://查询单个
                Log.i("test","查询单个");
               Long id= ContentUris.parseId(uri);
                return  sqLiteDatabase.query(false,"person",projection,"_id=?",new String[]{id+""},null,null,sortOrder,null);
        }
            return null;
    }
    @Nullable
    @Override
    public String getType(Uri uri) {
        Log.i("test","getType");
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        Log.i("test","insert");
        sqLiteDatabase.insert("person",null,values);
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        Log.i("test","delete");
        sqLiteDatabase.delete("person",selection,selectionArgs);
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        Log.i("test","update");
        return sqLiteDatabase.update("person",values,selection,selectionArgs);
    }
}

ContentResolver内容访问者:

 //控件初始化
       private void initWight() {
          button = (Button) findViewById(R.id.bt_main_button);
          et_main_id = (EditText) findViewById(R.id.et_main_id);//查询
          et_main_insertname = (EditText) findViewById(R.id.et_main_insertname);
          et_main_insertage = (EditText) findViewById(R.id.et_main_insertage);
           et_main_delete = (EditText) findViewById(R.id.et_main_delete);
           et_main_updateid = (EditText) findViewById(R.id.et_main_updateid);
           et_main_updatename = (EditText) findViewById(R.id.et_main_updatename);
           et_main_updateage = (EditText) findViewById(R.id.et_main_updateage);
           //01直接qurey询
           //02.http://localhost:8080/xxx.action?=1
           //使用uri匹配器
      }

    //查询
    public void getData(View view){
        //判断输入框是否为空
        if (TextUtils.isEmpty(et_main_id.getText().toString())){
            uri = Uri.parse("content://com.example.contentprivoid.MyPerson/linkman");
        }else{
            //单询单个
            String id=et_main_id.getText().toString();
            uri = Uri.parse("content://com.example.contentprivoid.MyPerson/linkman/"+id);
        }
        //访问数据
        Cursor cursor=cr.query(uri,null,null,null,null);
        while (cursor.moveToNext()){
            int pid=cursor.getInt(cursor.getColumnIndex("_id"));;
            String uname=cursor.getString(cursor.getColumnIndex("name"));
            int age=cursor.getInt(cursor.getColumnIndex("age"));
            Log.i("test",pid+"  "+uname+"  "+age);
        }

    }
    //添加
    public void addlinkman(View view){
        if (TextUtils.isEmpty(et_main_insertname.getText().toString())&&TextUtils.isEmpty(et_main_insertage.getText().toString())){
            Toast.makeText(this,"请填写完整",Toast.LENGTH_SHORT).show();
        }else{
            String name= et_main_insertname.getText().toString();
            String age=  et_main_insertage.getText().toString();
            ContentValues values=new ContentValues();
            values.put("name",name);
            values.put("age",age);
            uri = Uri.parse("content://com.example.contentprivoid.MyPerson");
            cr.insert(uri,values);
            Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
        }
    }

    //删除
    public void deletelinkman(View view){
        String id=et_main_delete.getText().toString();
        uri = Uri.parse("content://com.example.contentprivoid.MyPerson");
        cr.delete(uri,"_id=?",new String[]{id+""});
    }
    //修改
    public void updatelinkman(View view){
        String id=et_main_updateid.getText().toString();
        String name= et_main_updatename.getText().toString();
        String age=  et_main_updateage.getText().toString();
        uri = Uri.parse("content://com.example.contentprivoid.MyPerson");
        ContentValues values=new ContentValues();
        if (TextUtils.isEmpty(et_main_updatename.getText().toString())){

        }else {
            values.put("name",name);
        }
        if (TextUtils.isEmpty(et_main_updateage.getText().toString())){

        }else{
            values.put("age",age);
        }

        int update = cr.update(uri, values, "_id=?", new String[]{id + ""});
        if (update>0){
            Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"修改失败",Toast.LENGTH_SHORT).show();
        }
    }
基本代码就这些,清单文件的配置小编就粘贴啦,希望对初学者有帮助。大笑

ok,今天内容提供者就写到这,下次小编闲暇时间在学习内容提供者啦!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章