我是SQLite的新手,我试图按降序对我的COLUMN_PRICE进行排序并显示结果。我已经搜索了有关该主题的答案,但是到目前为止,对于我的情况,仍然没有帮助(甚至使用原始查询String selectQuery = "SELECT * FROM "+ TABLE_NAME + " ORDER BY " + COLUMN_PRICE + " DESC";
)。
或者,如何在列表视图中对SQLite输出进行排序-更好的选择。
请在下面查看我当前的方法:
private void sortByPrice() {
Cursor rowsOrdered = getContentResolver().query(Contract.Entry.CONTENT_URI, null, null, null, COLUMN_PRICE + " DESC", null);
Log.v("CatalogActivity", rowsOrdered + " rows ordered by price from database");
}
在这里从以下位置调用该方法:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//sort by price from lowest upon the button click
case R.id.action_sort_by_price:
sortByPrice();
return true;
}
return super.onOptionsItemSelected(item);
}
我在Provider中的游标查询如下:
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
boolean useAuthorityUri = false;
// Get readable database
SQLiteDatabase database = mDbHelper.getReadableDatabase();
// This cursor will hold the result of the query
Cursor cursor;
// Figure out if the URI matcher can match the URI to a specific code
int match = sURIMatcher.match(uri);
switch (match) {
case PRODUCT:
// For the PRODUCT code, query the table directly with the given
// projection, selection, selection arguments, and sort order. The cursor
// could contain multiple rows of table.
cursor = database.query(InventoryEntry.TABLE_NAME,
projection, selection, selectionArgs, null, null,
sortOrder);
break;
case PRODUCT_ID:
// For the PRODUCT_ID code, extract out the ID from the URI.
// For every "?" in the selection, we need to have an element in the selection
// arguments that will fill in the "?". Since we have 1 question mark in the
// selection, we have 1 String in the selection arguments' String array.
selection = Entry._ID + "=?";
selectionArgs = new String[]{String.valueOf((ContentUris.parseId(uri)))};
//query
cursor = database.query(Entry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
break;
default:
throw new IllegalArgumentException("No match found");
}
// notify all listeners of changes:
// getContext().getContentResolver().notifyChange(uri, null);
// if we want to be notified of any changes:
if (useAuthorityUri) {
cursor.setNotificationUri(
getContext().getContentResolver(),
InventoryContract.BASE_CONTENT_URI);
} else {
cursor.setNotificationUri(
getContext().getContentResolver(),
uri);
}
return cursor;
}
日志中没有错误(Log.v.中的消息按预期显示,尽管在应用程序中单击按钮时未发生任何事情。)
我在哪里做错了什么?
非常感谢您的帮助!
P.S。如我所知,我在Catalog Activity中的方法不起作用,因为它在Provider中没有覆盖主要方法(如果我在那进行排序,它可以工作,但是默认情况下是排序,而不是单击按钮)。 如何在单击按钮时添加我的排序方法,并在提供者中保留默认顺序?