首页 > 代码库 > 内容提供者学习笔记

内容提供者学习笔记

##内容提供者笔记##
###步骤###
1、创建实现了ContentProvider的子类MyContentProvider并重写父类的方法

2、作为android四大组件之一,要在manifest.xml文件中注册provider标签

    <provider
            android:name="cn.itcast.db.MyContentProvider"
            android:authorities="cn.itcast.db.persondb" >
    </provider>
>其中
>**name**为Myprovider所在的文件路径;
>**authorities**为自定义内容,但最好应顾名思义(应为数据库所在的包名/数据库名)

3、创建UriMatcher对象,参数舒适化为 **-1**

        public static UriMatcher urimacher = new UriMatche(-1);

4、在静态代码块中增加uri路径

        static{
            urimacher.addURI("cn.itcast.db.persondb","query",1);
            urimacher.addURI("cn.itcast.db.persondb","insert",2);
            urimacher.addURI("cn.itcast.db.persondb","delete",3);
            urimacher.addURI("cn.itcast.db.persondb","update",4);
            //content://cn.itcast.db.persondb/insert
            //content://cn.itcast.db.persondb/delete
            //content://cn.itcast.db.persondb/update
            //content://cn.itcast.db.persondb/query
        }
5、重写query方法时

    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        // TODO Auto-generated method stub
        int result = urimacher.match(uri);
        if(result==1){
            SQLiteDatabase db = sqlite.getReadableDatabase();
            return db.query("info", projection, selection, selectionArgs, null, null, sortOrder);
        }else{
            throw new RuntimeException("路径错误,请求得到数据失败");
        }
    }
6、在其他应用程序中通过内容提供者获取内容

     Uri uri = Uri.parse("content://cn.itcast.db.persondb/query");
        Cursor cursor = resolver.query(uri, null, null, null, null);
        while(cursor.moveToNext()){
            int id = cursor.getInt(cursor.getColumnIndex("_id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            System.out.println(id+"--"+name+"--"+phone);
        }
        cursor.close();
*根据内容提供者中已添加的uri路径进行使用*
**//content://cn.itcast.db.persondb/insert
  //content://cn.itcast.db.persondb/delete
  //content://cn.itcast.db.persondb/update
  //content://cn.itcast.db.persondb/query**

内容提供者学习笔记