我正在尝试创建一个游标加载器,我想在其中查询两个项目的特定列,类似于:
SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN(something, something_else);
return new CursorLoader(getActivity(),
myUri,
null,
MyContract.FoodEntry.COLUMN_TYPE + " = ? ",
selectionArgs,
null);
不知道selectionArgs(这是一个String数组)应该是什么样子。有什么办法可以实现我想要的实现吗?
最佳答案
您将需要使用LIKE
关键字,并使用%
在something
和something_else
的任一侧指定通配符。
另外,您可能应该使用实例变量来存储两个字符串,因为我不确定如何将它们传递给onCreateLoader()
。
我只是通过查询设备上的联系人对此进行了测试,它将使您了解如何使用selectionArgs
。
请注意,对于?
参数中的每个selection
,在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);
}
请参见Documentation Here。
因此,对于您的特定示例,将如下所示:
String[] selectionArgs = {"%" + something + "%" , "%" + something_else + "%" };
return new CursorLoader(getActivity(),
myUri,
null,
MyContract.FoodEntry.COLUMN_TYPE + " LIKE ? OR " + MyContract.FoodEntry.COLUMN_TYPE + " 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);
}
}
我还让Activity实现了
LoaderManager.LoaderCallbacks
接口:public class MainActivity extends ActionBarActivity implements
LoaderManager.LoaderCallbacks<Cursor>{