我正在尝试:
- 显示联系人列表
- 让用户通过键入查询来搜索它们
- 将搜索结果限制为仅限特定的 Google/Gmail 帐户。
这是我为游标构建 URI 的方式:
// User is searching for 'jo'
String query = "jo";
Uri uri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI, Uri.encode(query));
// Restrict the query to contacts from 'example@gmail.com'
Uri.Builder builder = uri.buildUpon();
builder.appendQueryParameter(
ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(ContactsContract.Directory.DEFAULT));
builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "example@gmail.com");
builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.google");
uri = builder.build();
这是最后一个 URI:
content://com.android.contacts/contacts/filter/jo?directory=0&account_name=example%40gmail.com&account_type=com.google
目前,这将显示手机上所有帐户的搜索结果。
注意:如果我使用 Contacts.CONTENT_URI
而不是 Contacts.CONTENT_FILTER_URI
,则指定目录/帐户可以按预期工作,但我不能再使用"类型到过滤器"样式搜索。
该文档确实指出:
目录最重要的用例是搜索。目录 提供程序应至少支持
Contacts.CONTENT_FILTER_URI
个。
谁能帮助指出我可能做错了什么?
我在Google的示例中添加了您的代码以进行联系人检索,并且进行了一些更改,它与我的Google for Work帐户完美配合。
我所做的更改是:
- 删除带有
DIRECTORY_PARAM_KEY
的行,因为我发现它没有任何区别 - 从 return 语句中删除了
ContactsQuery.SELECTION
,因为该常量会阻止显示"不可见"联系人。
更改是对联系人列表片段进行的.java
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// If this is the loader for finding contacts in the Contacts Provider
// (the only one supported)
if (id == ContactsQuery.QUERY_ID) {
Uri contentUri;
// There are two types of searches, one which displays all contacts and
// one which filters contacts by a search query. If mSearchTerm is set
// then a search query has been entered and the latter should be used.
if (mSearchTerm == null) {
// Since there's no search string, use the content URI that searches the entire
// Contacts table
contentUri = ContactsQuery.CONTENT_URI;
} else {
// Since there's a search string, use the special content Uri that searches the
// Contacts table. The URI consists of a base Uri and the search string.
contentUri = Uri.withAppendedPath(ContactsQuery.FILTER_URI, Uri.encode(mSearchTerm));
}
// HERE COMES YOUR CODE (except the DIRECTORY_PARAM_KEY line)
Uri.Builder builder = contentUri.buildUpon();
builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "example@mycompany.com");
builder.appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.google");
contentUri = builder.build();
// Returns a new CursorLoader for querying the Contacts table. No arguments are used
// for the selection clause. The search string is either encoded onto the content URI,
// or no contacts search string is used. The other search criteria are constants. See
// the ContactsQuery interface.
return new CursorLoader(getActivity(),
contentUri,
ContactsQuery.PROJECTION,
null, // I REMOVED SELECTION HERE
null,
ContactsQuery.SORT_ORDER);
}
Log.e(TAG, "onCreateLoader - incorrect ID provided (" + id + ")");
return null;
}