我需要使用其唯一的_ID将光标加载到多个联系人。我可以获得所有联系人的列表,但是我遇到了CursorLoader的SELECTION参数问题。
到目前为止我所拥有的是:
private static final String SELECTION = Contacts._ID + " IN (?)";
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Uri contentUri = Contacts.CONTENT_URI;
String selection[] = new String[1];
selection[0] = "8,50";
return new CursorLoader(getActivity(), contentUri, PROJECTION,
SELECTION, selection, null);
}
这返回没有行。如果我将选择数组更改为
selection[0] = "8"
然后它正确地返回_ID为8的联系人。
任何人对如何使用_ID检索多个联系人有什么想法?
提前致谢。
答案 0 :(得分:1)
您需要使用id in (?,?)
来选择2个项目,如果您选择了多个IDs
,则必须将(?,?,..)
与选择项目的数量相同。然后在IDs
数组中列出selectionArgs[]
列表,如下所示:
String[] projection =...
String selectionArgs[] = {"8","50"};
String selection = Contacts._ID + " in (";
for (int i = 0; i < selectionArgs.length; i++) {
selection += "?, ";
}
selection = selection.substring(0, selection.length() - 2) + ")";
return new CursorLoader(getActivity(), contentUri, projection,
selection, selectionArgs, null);
答案 1 :(得分:0)
我做了一个快速测试,发现这个sql语句对我有用:
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ) AND ("
+ Contacts._ID + " in (369, 330)))";
此处的代码段:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
Uri.encode(mCurFilter));
} else {
baseUri = Contacts.CONTENT_URI;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ) AND ("
+ Contacts._ID + " in (369, 330)))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
对于您正在使用的其他选项,我也对其进行了测试。如果您确实想使用selectParameters,请以这种方式使用它:
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ) AND ("
+ Contacts._ID + " in (?,?)))";
String selectionParams[] = new String[2];
selectionParams[0] = "369";
selectionParams[1] = "330";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, selectionParams,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
希望这对你有帮助。