Android 为单个db列在SelectionAgs中创建一个包含多个项目的光标
我正在尝试创建一个游标加载器,在其中我要查询两个项目的特定列,类似于:Android 为单个db列在SelectionAgs中创建一个包含多个项目的光标,android,Android,我正在尝试创建一个游标加载器,在其中我要查询两个项目的特定列,类似于: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN(something, something_else); return new CursorLoader(getActivity(), myUri, null, MyContract.FoodEntry.COLUMN_TYPE + " =
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN(something, something_else);
return new CursorLoader(getActivity(),
myUri,
null,
MyContract.FoodEntry.COLUMN_TYPE + " = ? ",
selectionArgs,
null);
不确定SelectionAgs(一个字符串数组)应该是什么样子。有什么方法可以通过这个实现实现我想要的吗?您需要使用
LIKE
关键字并使用%
在某物和某物的任一侧指定通配符
另外,您可能应该使用实例变量来存储这两个字符串,因为我不确定如何将它们传递到onCreateLoader()
我只是通过查询我设备上的联系人来测试这一点,它会让您了解如何使用selectionArgs
请注意,对于选择
参数中的每个?
,您需要在selectionArgs
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Uri CONTENT_URI = ContactsContract.RawContacts.CONTENT_URI;
String s1 = "Dan";
String s2 = "nugent";
String[] selectionArgs = {"%" + s1 + "%" , "%" + s2 + "%" };
return new CursorLoader(this, CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " LIKE ? OR " + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " LIKE ?", selectionArgs, null);
}
此外,为了以防万一,这是我在测试中检索值的方式:
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
if (cursor.moveToFirst()) {
StringBuilder res = new StringBuilder();
while (!cursor.isAfterLast()) {
res.append("\n" + cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)));
cursor.moveToNext();
}
textView.setText(res);
}
}
非常感谢你!你是个救生员@Andreistangcianu当然,没问题!
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
if (cursor.moveToFirst()) {
StringBuilder res = new StringBuilder();
while (!cursor.isAfterLast()) {
res.append("\n" + cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)));
cursor.moveToNext();
}
textView.setText(res);
}
}
public class MainActivity extends ActionBarActivity implements
LoaderManager.LoaderCallbacks<Cursor>{