码迷,mamicode.com
首页 > 移动开发 > 详细

Android四大组件之——ContentProvider(二)

时间:2014-10-20 00:49:14      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:des   android   style   blog   http   color   io   os   ar   

Content Resolver介绍:

   开发者文档中这么定义的:

This class provides applications access to the content model.

这个类为应用提供访问Content模型的功能。

Content Resolver是我们应用里单一全局实例,为我们访问我们自己的应用或其他应用的Content Provider。就如同名字所描述的:Content Resolver接收来自客户的请求,然后解决它们的请求,通过将请求指向特定主机名的Content Provider解决。

 

Content Resolver包括了CRUD方法(create,read,update,delete)。这些正好与Content Provider中的抽象方法

                 (insert ,query,update,delete)一 一对应。

bubuko.com,布布扣

                 (图转自http://www.cnblogs.com/plokmju/p/android_ContentProvider.html)

 

Content Resolver不知道Content Provider是怎样对数据操作的,也不需要知道。Content Resolver的每个方法通过传递

URI到特定的Content Provider来实现对数据产生影响的操作。

bubuko.com,布布扣

 下面我将通过一个Content Resolver的Demo实现对Android系统的User Dictionary进行增删改查操作。

  增加(insert):

 

//调用getContentResolver()获取ContentResolver对象
ContentResolver contentResolver = getContentResolver;
ContentValues values = new ContentValues();
values.put(Words.WORD,"NewWord");     

//调用ContentResolver.insert(Uri url, ContentValues values)方法增加数据
contentResolver.insert(UserDictionary.Words.CONTENT_URI, values);

 

删除(delete):

//调用ContentResolver.delete(Uri url, String where, String[] selectionArgs)
//方法删除数据,返回的是删除的行数
long deleted = cr.delete(Words.CONTENT_URI,Words.WORD + "= ?", new String[]{"NewWord"});

查找(query):

String [] projection = new String[]{
                BaseColumns._ID,
                UserDictionary.Words.WORD
        };
Cursor cursor =cr
                .query(UserDictionary.Words.CONTENT_URI,
                        projection, 
                        null,
                        null,
                        null);
 if(cursor.moveToFirst()){
            do{
                long id = cursor.getLong(0);
                String word= cursor.getString(1);
                Map<String,Object>map = new HashMap<String,Object>();
                
                map.put("id", id);
                map.put("word", word);
                list.add(map);
            }while(cursor.moveToNext());

修改(update):

//调用ContentResolver.update(Uri uri, ContentValues values, String where, //String[] selectionArgs)方法更新数据
//返回更新行数的个数
long update = cr.update(uri, values, null, null);

 

应用截图:                                                                                       用户字典截图:

bubuko.com,布布扣                         bubuko.com,布布扣

  本人邮箱:JohnTsai.Work@gmail.com,欢迎交流讨论。      

  欢迎转载,转载请注明网址:http://www.cnblogs.com/JohnTsai

Android四大组件之——ContentProvider(二)

标签:des   android   style   blog   http   color   io   os   ar   

原文地址:http://www.cnblogs.com/JohnTsai/p/4035138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!