ContentResolver.query详解

2023-05-16

1.查询手机的联系人
    public void getContacts() {
        ContentResolver contentResolver = this.getContentResolver();
        Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            do {
                Log.d(TAG,cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID)));
                Log.d(TAG,cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME)));
            } while (cursor.moveToNext());
        }
        cursor.close();
    }

记得开权限

 <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />

log

05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 1
05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 阿大
05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 2
05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 阿牛
05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 3
05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 阿虎
05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 4
05-08 16:20:08.639 7447-7447/com.bbk.contentprovidertest D/notecontent: 海哥
cusor的正确遍历方式

查询得到的cursor是指向第一条记录之前的,因此查询得到cursor后第一次调用moveToFirst或moveToNext都可以将cursor移动到第一条记录上。但是为了规避一些可能存在的情况,下面这种写法比较保险

if (cursor != null && cursor.moveToFirst())
{
      do{

      }while(cursor.moveToNext());
}
cursor.close();

这篇文章主要讲解ContentResolver的query方法。

ContentResolver直译为内容解析器,什么东东?Android中程序间数据的共享是通过Provider/Resolver进行的。提供数据(内容)的就叫Provider,Resovler提供接口对这个内容进行解读。

根据Android文档,

public final Cursor query (Uri uri, String[] projection,String selection,String[] selectionArgs,String sortOrder)

第一个参数,uri

uri是什么呢?好吧,上面我们提到了Android提供内容的叫Provider,那么在Android中怎么区分各个Provider?有提供联系人的,有提供图片的等等。所以就需要有一个唯一的标识来标识这个Provider,Uri就是这个标识,android.provider.ContactsContract.Contacts.CONTENT_URI就是提供联系人的内容提供者,可惜这个内容提供者提供的数据很少。

第二个参数,projection,

这个参数告诉Provider要返回的内容(列Column),比如Contacts Provider提供了联系人的ID和联系人的NAME等内容,如果我们只需要NAME,那么我们就应该使用:

Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,  
    new String[]{android.provider.ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);  

当然,下面打印的你就只能显示NAME了,因为你返回的结果不包含ID。用null表示返回Provider的所有内容(列Column)。
Log

05-08 16:00:55.587 13524-13524/com.bbk.contentprovidertest D/notecontent: 阿大
05-08 16:00:55.588 13524-13524/com.bbk.contentprovidertest D/notecontent: 阿牛
05-08 16:00:55.588 13524-13524/com.bbk.contentprovidertest D/notecontent: 阿虎
05-08 16:00:55.588 13524-13524/com.bbk.contentprovidertest D/notecontent: 海哥

第三个参数,selection,

设置条件,相当于SQL语句中的where。null表示不进行筛选。如果我们只想返回名称为“海哥”的数据,第三个参数应该设置为:

 Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,
                new String[]{ContactsContract.Contacts.DISPLAY_NAME}, ContactsContract.Contacts.DISPLAY_NAME + "= '海哥'", null, null);//注意‘海哥’ 

获取到的结果,Log

05-08 16:05:16.264 20723-20723/com.bbk.contentprovidertest D/notecontent: 海哥

例如查询手机中以.txt结尾的文件

Cursor cursor = getContentResolver().query(
                Uri.parse("content://media/external/file"),
                projection,
                MediaStore.Files.FileColumns.DATA + " like ?" ,
                new String[]{"%.txt"},
                null);

SQL模糊查询语句

先看下面这个函数,查询手机中以.txt结尾的文件以及文档大小要超过500KB的文档。

  private void queryBooks() {
        String[] projection = new String[]{MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE};
        //查询以.txt结尾的文件以及文件大小超过1024*500(500KB)
        //注意 AND  俩边空格 
        Cursor cursor = getContentResolver().query(
                Uri.parse("content://media/external/file"),
                projection,
                MediaStore.Files.FileColumns.DATA + " like ?" + " AND " + MediaStore.Files.FileColumns.SIZE + " >= ?",
                new String[]{"%.txt", "512000"},
                null);
        if (cursor != null && cursor.moveToFirst()) {
            do {
                int ctitle = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
                int csize = cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE);
                Recommend.RecommendBooks books = new Recommend.RecommendBooks();
                long size = cursor.getLong(csize);
                String title = cursor.getString(ctitle);
                int dot = title.lastIndexOf("/");
                String name = title.substring(dot + 1);
                if (name.lastIndexOf(".") > 0) {
                    name = name.substring(0, name.lastIndexOf("."));
                }
                books.title = name;
                books.lastChapter = FileUtils.formatFileSizeToString(size);
                books.isFromSD = true;
                mList.add(books);
            } while (cursor.moveToNext());
          
        }
        cursor.close();
        mAdapter.setListItems(mList);
        mAdapter.notifyDataSetChanged();
        mListView.setAdapter(mAdapter);

    }

上面这段代码直接在查询时,就明确了要求,查询效率也大幅度提升,比在查询后根据size再次判断快了200多毫秒。

SQL模糊查询,使用like比较字,加上SQL里的通配符:

like使用:

下面一些实例演示了 带有 ‘%’ 和 ‘_’ 运算符的 LIKE 子句不同的地方:

语句描述
WHERE SALARY LIKE ‘200%’查找以 200 开头的任意值
WHERE SALARY LIKE ‘%200%’查找任意位置包含 200 的任意值
WHERE SALARY LIKE ‘_00%’查找第二位和第三位为 00 的任意值
WHERE SALARY LIKE ‘2_%_%’查找以 2 开头,且长度至少为3个字符的任意值
WHERE SALARY LIKE ‘%2’查找以 2 结尾的任意值
WHERE SALARY LIKE ‘_2%3’查找第二位为 2,且以 3 结尾的任意值
WHERE SALARY LIKE ‘2___3’查找长度为 5位数,且以2开头以3结尾的任意值

第四个参数,selectionArgs,

这个参数是要配合第三个参数使用的,如果你在第三个参数里面有?,那么你在selectionArgs写的数据就会替换掉?,

  Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,
                new String[]{ContactsContract.Contacts.DISPLAY_NAME}, ContactsContract.Contacts.DISPLAY_NAME + "= ?", new String[]{"海哥"}, null);

效果和上面一句的效果一样。

第五个参数,sortOrder,

按照什么进行排序,相当于SQL语句中的Order by。如果想要结果按照ID的降序排列:

Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,  
                null, null,null, android.provider.ContactsContract.Contacts._ID + " DESC");

Log

05-08 16:18:11.061 4921-4921/com.bbk.contentprovidertest D/notecontent: 海哥
05-08 16:18:11.061 4921-4921/com.bbk.contentprovidertest D/notecontent: 阿虎
05-08 16:18:11.061 4921-4921/com.bbk.contentprovidertest D/notecontent: 阿牛
05-08 16:18:11.061 4921-4921/com.bbk.contentprovidertest D/notecontent: 阿大

升序,默认排序是升序,也可+" ASC":


Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,  
                null, null,null, android.provider.ContactsContract.Contacts._ID + " ASC"); 

Log

05-08 16:18:53.787 6316-6316/com.bbk.contentprovidertest D/notecontent: 阿大
05-08 16:18:53.787 6316-6316/com.bbk.contentprovidertest D/notecontent: 阿牛
05-08 16:18:53.787 6316-6316/com.bbk.contentprovidertest D/notecontent: 阿虎
05-08 16:18:53.787 6316-6316/com.bbk.contentprovidertest D/notecontent: 海哥

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ContentResolver.query详解 的相关文章

  • ContentResolver.query详解

    1 查询手机的联系人 public void getContacts ContentResolver contentResolver 61 this getContentResolver Cursor cursor 61 contentRe
  • docker mysql:5.6镜像安装mysqlreport、pt-query-digest

    更新debian源 echo 34 deb http ftp cn debian org debian stretch main 34 gt etc apt sources list echo 34 deb http ftp cn debi
  • mysql_query()和myql_real_query()的区别

    函数原型 span class token keyword int span span class token function mysql query span span class token punctuation span MYSQ
  • JPA的@Query用法

    文章目录 64 Query作用使用例子简单使用like表达式原生sql 传参方式SPEL表达式nativeQuery 作用更新操作删除操作 64 query返回自定义字段 64 query返回自定义对象 64 Query作用 64 Quer
  • Elasticsearch使用update_by_query

    elasticsearch中有一个方法是批量修改 xff0c 就是先查询出需要修改的索引记录 xff0c 然后批量修改 这个本来没什么 xff0c 但是使用过的都知道 xff0c 用java来调用这个方法很别扭 一般来说 xff0c 我们使
  • http请求参数之Query String Parameters、Form Data、Request Payload

    在与server端进行数据传递时 xff0c 通常会用到GET POST方法进行参数提交 xff0c 而参数提交的方式 xff0c 通常取决于server端对数据的接收方式 本文对几种常见的参数提交方式进行归纳及简述 xff0c 这不是一篇
  • 使用pt-query-digest分析mysql

    最近在看 高性能MySQL xff0c 作者们背靠Percona向我展示了以前从不知道的一些关于MySQL的知识以及各种分析优化工具 xff0c 比如这里要说的pt query digest 什么是pt query digest pt qu
  • Lucene Query Parser 语法

    lucene的组合条件语法 xff0c 看了网上很多文章 xff0c 真的都太差了 还是官网清晰明了一点 SKIP NAVIGATION LINKS OVERVIEWPACKAGECLASSUSETREEDEPRECATEDHELP PRE
  • ContentResolver.query详解

    1 查询手机的联系人 public void getContacts ContentResolver contentResolver 61 this getContentResolver Cursor cursor 61 contentRe
  • Scheduling and emailing PeopleSoft Query results

    You could E Mail the Query results by embedding the paramters in a nVision Layout Create a Tabular nVision Layout Add th
  • elk笔记13--Query DSL

    elk笔记13 Query DSL 1 基础介绍 2 常见查询类型 2 1 Query and filter context 2 2 Compound queries 2 3 Full text queries 2 4 Geo querie
  • Subquery and Wrapping query

    Subquery Progressive query Into Wrapping query 1 Using fluent syntax string names Tom Dick Harry Mary Jay IEnumerable
  • Android中的Cursor到底是什么?如何理解Cursor的方法都在做什么事情?

    一 Cursor到底是什么 网上很多博客都介绍了Cursor 介绍了各种概念 各种原理 可是有的小伙伴可能还是很懵逼 这特码的到底都是什么 刚开始接触Cursor的时候也是一脸懵逼 看到人家说这个方法是在干什么干什么 可以脑子里没有一个生动
  • elk笔记13--Queries-term-level queries

    elk笔记13 Queries term level queries 1 term level 查询简介 2 term level 查询类型 2 1 exists query 2 2 fuzzy query 2 3 ids query 2
  • c++ primer 中的文本查询示例

    前言 有个牛人叫bnu chenshuo 发微博说 回复 TheRealBo 学生编程练习 把 Unix 的命令行小工具用C C 实现一遍 wc cat ls cp grep sort uniq nc head tail hexdump 把
  • Hql

    1 查询整个映射对象所有字段 直接from查询出来的是一个映射对象 即 查询整个映射对象所有字段 String hql from Users Query query session createQuery hql List
  • MySQL日志设置及查看

    MySQL有以下几种日志 错误日志 log err 查询日志 log 慢查询日志 log slow queries 更新日志 log update 二进制日志 log bin 默认情况下 所有日志创建于mysqld数据目录中 通过刷新日志
  • 有discuz数据库,忘了管理员密码,怎样进后台

    很简单 你注册一个用户 密码设个简单一点的 然后在ucenter的数据库中uc members表中找到这个用户的password字段和salt字段 把你在uc members表中的管理员账号的password和salt字段修改成新注册用的的
  • CSS中设置表格TD宽度的问题

    CSS布局 表格宽度不听使唤的实例 想把表格第一例宽度设为20 其他自适应 但CSS中宽度是等宽的 只设这一行也不起作用 但是在实际应用中总是等宽处理 并不按照样式来走 XML HTML代码
  • OceanBase使用范例

    http www mysqlops com 2011 08 31 oceanbase use html OceanBase的使用类似于关系型数据库 需要预先创建schema 关于schema的格式 请参见schema说明 假如我们有以下sc

随机推荐

  • 长虹官方刷机包和刷机教程

    为了解决部分朋友因应用引起的电视死机 无法开机 系统被破坏等情形 xff0c 长虹电视团队特开此帖为朋友们提供刷机方法 xff0c 但刷机有风险 xff0c 如完全不懂刷机技巧的朋友需要谨慎操作哦 xff0c 如有疑问可以微信留言给我们 下
  • Android终端通过adb 配置静态IP和DNS

    有时我们需要使用命令行来配置eth0的IP信息 xff0c 这在linux系统是非常简单的 xff0c 网上也有很多资料 但是在Android系统 xff0c 就非常困难 xff0c 因为Android精简掉了很多linux命令 xff0c
  • 【官方】下载最新adb及安装驱动的方法

    Only adb 驱动 xff1a https adbdriver com downloads adb工具 xff1a https adbshell com upload adb zip https adbshell com downloa
  • 中芯微随身WIFI破解实体SIM卡槽(不拆机,无需切卡密码)

    目前网上卖的一些随身WIFI是中芯微的方案 MF782 部分产品限制用户使用实体SIM卡 只能使用内置eSIM 下面谈谈解决方案 1 中沃的没有限制 实体SIM卡优先 检测到插的有实体SIM卡 就使用实体SIM卡网络 2 另外一部分网上提供
  • 高通Android随身WIFI屏蔽商家远程控制断网

    nbsp nbsp nbsp nbsp 部分随身WIFI商家后台会监测用户是否使用的是自家的eSIM 若使用了外置卡槽或eSIM的ICCID改变就会断网 主要表现是先联网后突然变成飞行模式 或联网后开热点变飞行模式 这就是商家后台做了监测
  • Linux kernel make clean时忽略部分文件(不被删除)

    有时我们在运行make clean 时 xff0c 需要保留某些 o 文件 xff0c 这就需要我们修改 Makefile 文件 xff0c 下面以 linux 2 6 18 的 Makefile 为例 xff1a Files to ign
  • Audio参数讲解

    一 音频基础参数 frame bits 一帧数据的位数比如 xff1a 16bits 2ch frame bits 61 16 2 sample bits 采样位数 比如16bit 24bit 32bit period size 指一个周期
  • linux ALSA 驱动架构

    一 kernel Audio驱动架构主流有两大类 xff0c 一类是SOC Machine架构 xff0c 另一类是simple card架构 MTK QCom主要采用machine架构 xff0c rockchip采用simple car
  • adaboost提升算法

    引言 俗话说得好 xff0c 三个臭皮匠赛过诸葛亮 更主要的是三个臭皮匠好找 xff0c 一个诸葛亮太难找了 在机器学习里面也是一样的 我们可以设计出各种分类器 xff0c 然而分类器的效果确实不一而同的 xff0c 相对而言 xff0c
  • 长虹电视刷机固件包汇总

    为了解决部分朋友因应用引起的电视死机 无法开机 系统被破坏等情形 xff0c 快客服务特开此帖为朋友们提供刷机方法 xff0c 但刷机有风险 xff0c 如完全不懂刷机技巧的朋友需要谨慎操作 xff0c 用户自行刷机所产生问题自行负责 xf
  • WebRTC-集成qsv硬解码实现

    1 Window下QSV硬解码配置 在libavcodec codec list c下添加 amp ff h264 qsv decoder 在ffmpeg generate gni下加入 34 libavcodec h264idct c 3
  • ijkplayer-添加播放截图功能

    应用播放的时候需要截图 xff0c 可以在上层使用TexturView来使用截图 xff0c 不过太具有局限性呢 xff0c 还是在底层处理比较好 那么先分析下可以在哪里加截图呢 xff1f 看到网上很多做的都不能支持硬解截图 xff0c
  • avformat_seek_file及其flag含义

    我们从ijk中seek的处理流程来看ffmpeg的这个问题 int ffp seek to l FFPlayer ffp long msec assert ffp VideoState is 61 ffp gt is int64 t sta
  • 单例模式

    单例模式 xff1a include lt iostream gt using namespace std class Singleton public Singleton cout lt lt 34 Singleton虚构函数 34 lt
  • ffmpeg系列-解决ffmpeg获取aac音频文件duration不准

    这个问题是这样产生的 xff0c 一同事反应会随机出现ijk获取到的aac文件的duration不准 xff0c 发来一看 xff0c 确实不准 xff0c 在AE或者系统mediaplayer中得到的都是8 4秒 xff08 准确时间是M
  • 基于librtmp的推流实现

    1 推流 配置好rtmpdump库后 xff0c 我们可以先用命令行来推流看下效果 2 流程图 使用librtmp发布RTMP流的可以使用两种API xff1a RTMP SendPacket 和RTMP Write 使用RTMP Send
  • ijkplayer-音视频变速播放实现

    本文主要分析变速播放框架实现细节 xff0c 不分析sonic以及soundtouch变速算法 在我的sonic变速变调原理一文中会详细讲解基于基音周期来实现变速变调的原理 1 变速入口分析 从jni层的 setPropertyFloat函
  • 提升树,bagging与随机森林

    提升树是一种以分类树或者回归树为基本分类器的提升方法 对于分类树只需将adaboost算法中的基函数设置为二分类二叉树即可 而回归树则是根据残差来训练下一个分类器的回归二叉树 下面主要介绍一下回归提升树的算法 回归提升树 回忆一下 xff0
  • Android_WakeLock使用

    1 前言与WakeLock简介 1 1 前言 一些手机app xff08 如微信 QQ等 xff09 有新消息来到达 xff0c 手机屏幕即使在锁屏状态下也会亮起 xff0c 并提示用户有新消息 但是 xff0c 一般情况下手机锁屏后 xf
  • ContentResolver.query详解

    1 查询手机的联系人 public void getContacts ContentResolver contentResolver 61 this getContentResolver Cursor cursor 61 contentRe