android 多线程 之 ContentProvider

来源:互联网 发布:爱上人工智能 编辑:程序博客网 时间:2024/06/18 17:05

内容提供者对数据的访问提供了同一的接口.
内容解析者通过一定格式的uri,访问内容提供者的内部.内容提供者中的方法通过传过来的路径和匹配规则来判断进行不同的操作.

使用自定义内容提供者.实现一个类继承ContentProvider,实现未实现的方法.
然后,在功能清单内注册.

 <provider         android:name="com.example.mycontentprovider.Provider.PersonProvider" //配置访问的对外路径       android:authorities="com.example.mycontentprovider.provider.personprovider">     </provider>

最后在使用时,使用内容解析者,传入Uri地址,来操作内容提供者的方法.

         //定义匹配器    public static UriMatcher matcher=newUriMatcher(UriMatcher.NO_MATCH);//添加匹配规则static{    matcher.addURI(uri, "person", MULTI);       matcher.addURI(uri, "perosn/#", SINGLE);}uri为内容提供者authorities的值.//增加数据public Uri insert(Uri uri, ContentValues values) {    SQLiteDatabase base=db.getReadableDatabase();    try {        if(base!=null){            long id= base.insert("person","name", values);            //通知更改            resolver.notifyChange(uri, null);            return ContentUris.withAppendedId(uri, id);         }    } catch (Exception e) {        // TODO Auto-generated catch block        e.printStackTrace();    }finally{        if(base!=null){            base.close();        }    }    return null;}

删:

 public int delete(Uri uri, String selection, String[] selectionArgs) {     int code=matcher.match(uri);     SQLiteDatabase base=db.getWritableDatabase();     switch(code){     case MULTI:         try {            if(base!=null){                 return base.delete("person", selection, selectionArgs);             }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            if(base!=null){                base.close();            }        }         break;     case SINGLE:         long id=ContentUris.parseId(uri);         StringBuilder sb=new StringBuilder();         sb.append(" _id= "+id);         if(selection!=null){             sb.append(" and "+selection);         }         return base.delete("person", sb.toString(), selectionArgs);      default:          throw new RuntimeException("无效的Uri地址");     }    return 0;}

更新:

public int update(Uri uri, ContentValues values, String selection,        String[] selectionArgs) {    int code=matcher.match(uri);    SQLiteDatabase base=db.getWritableDatabase();    switch(code){    case MULTI:        return base.update("person", values, selection, selectionArgs);    case SINGLE:        long id=ContentUris.parseId(uri);        StringBuilder sb=new StringBuilder();        sb.append("_id="+id);        if(selection!=null){            sb.append(" and "+selection);        }        return base.update("person", values, sb.toString(), selectionArgs);      default:          throw new RuntimeException("无效的Uri地址");    }}

查询数据:

 public Cursor query(Uri uri, String[] projection, String selection,        String[] selectionArgs, String sortOrder) {    int code=matcher.match(uri);    SQLiteDatabase base=db.getReadableDatabase();    switch(code){    case MULTI:        Cursor cursor=base.query("person", projection, selection, selectionArgs, null, null, sortOrder);        return cursor;    case SINGLE:        long id=ContentUris.parseId(uri);        StringBuilder sb=new StringBuilder();        sb.append("_id="+id);        if(selection!=null){            sb.append(" and "+selection);        }        return base.query("person", projection, sb.toString(), selectionArgs,null,null, sortOrder);     default:         throw new RuntimeException("传入的地址有误.");    }}

//返回类型

public String getType(Uri uri) {    switch(matcher.match(uri)){    case MULTI:        return "vnd.android.cursor.dir/person";    case SINGLE:        return "vnd.android.cursor.item/person";  default:      throw new RuntimeException("无效的Uri地址");    }}

在功能清单中注册:

 <provider         android:name="com.example.mycontentproviderdemo.provider.PersonProvider"        android:authorities="com.example.mycontentproviderdemo.provider.personprovider"        android:exported="true">    </provider>

测试类:

测试添加数据:

public void testQueryUriStringArrayStringStringArrayString() {    Uri uri=Uri.parse("content://"+GlobalConstant.author+"/person");    Cursor cursor=resolver.query(uri, null,null, null, null);    List<Person> list=new ArrayList<Person>();    while(cursor.moveToNext()){        Person p=new Person();        int _id=cursor.getInt(cursor.getColumnIndexOrThrow("_id"));        String name=cursor.getString(cursor.getColumnIndexOrThrow("NAME"));        String address=cursor.getString(cursor.getColumnIndexOrThrow("address"));        int age=cursor.getInt(cursor.getColumnIndexOrThrow("age"));        p.set_id(_id);        p.setAddress(address);        p.setAge(age);        p.setName(name);        list.add(p);    }    Log.v("tag", list.toString());}

内容观察者:

private final class MyObServer extends ContentObserver{        public MyObServer(Handler handler) {            super(handler);            // TODO Auto-generated constructor stub        }        /**         * 当内容提供者对外发送消息后自动调用的方法,可以用来查询需要的数据         */        @Override        public void onChange(boolean selfChange) {            System.out.println("==ContentResover.MyObServer.onChange(boolean selfChange)===");        }    }

//注册内容观察者

 public void testInsertUriContentValues() {    ContentValues values=new ContentValues();    values.put("name", "斑");    values.put("age", 40);    values.put("address", "木叶");    Uri uri=Uri.parse("content://"+GlobalConstant.PERSON_AUTHORITY+"/person");    resolver.insert(uri, values);    //注册内容观察者    this.resolver.registerContentObserver(uri, true, new MyObServer(new Handler()));}
0 0
原创粉丝点击