Android ContentResolver如何查询数据

   2024-09-30 2910
核心提示:在Android中,ContentResolver是一个用于与其他应用程序共享数据的接口获取ContentResolver实例:ContentResolver contentResolv

在Android中,ContentResolver是一个用于与其他应用程序共享数据的接口

获取ContentResolver实例:
ContentResolver contentResolver = getContentResolver();

确定要查询的URI。URI通常指向一个内容提供者,它是一个包含您要查询的数据的应用程序。例如,要查询联系人数据,可以使用ContactsContract.Contacts.CONTENT_URI。

确定要查询的列。这是一个字符串数组,表示您想从内容提供者中检索的列名称。例如,要查询联系人的姓名和电话号码,可以使用以下列:

String[] projection = new String[]{    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,    ContactsContract.CommonDataKinds.Phone.NUMBER};
(可选)指定查询条件。这是一个WHERE子句,用于过滤结果集。例如,要查询姓氏为"Smith"的联系人,可以使用以下条件:
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " LIKE ?";String[] selectionArgs = new String[]{"%Smith%"};
(可选)指定排序顺序。这是一个ORDER BY子句,用于对结果集进行排序。例如,要按姓名排序,可以使用以下排序顺序:
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
使用ContentResolver的query()方法执行查询:
Cursor cursor = contentResolver.query(    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, // URI    projection,                                         // 要查询的列    selection,                                          // WHERE子句    selectionArgs,                                       // WHERE子句的参数    sortOrder                                            // ORDER BY子句);
处理查询结果。使用Cursor对象遍历结果集并处理数据。例如,打印每个联系人的姓名和电话号码:
if (cursor != null) {    while (cursor.moveToNext()) {        String displayName = cursor.getString(            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));        String phoneNumber = cursor.getString(            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));        Log.d("Contact", displayName + ": " + phoneNumber);    }    cursor.close();}

这就是如何使用Android的ContentResolver查询数据。请注意,查询不同的内容提供者可能需要不同的URI、列和查询条件。始终参考相应的文档以了解如何正确地查询特定的内容提供者。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号