ORDER BY DESC - SQLite-запрос по нажатию кнопки - с использованием getContentResolver () - Java Android - PullRequest
0 голосов
/ 26 февраля 2019

Я новичок в 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);
    }

Мой запрос курсора в провайдере выглядит так:

@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. отображается должным образом, хотя при нажатии кнопки в приложении ничего не происходит).

Где я что-то не так делаю?

Ваша помощь очень ценится!

PS Как я понял, мой метод в Activity по каталогам не работает, так как не переопределяет основной метод в Provider (если я сортирую там, это работает, но сортировка по умолчанию тогда, а не по нажатию кнопки).Как добавить мой метод сортировки по нажатию кнопки и оставить порядок по умолчанию в поставщике?

...