G
G
Grigory Kalyashov2015-09-21 11:58:34
Java
Grigory Kalyashov, 2015-09-21 11:58:34

How to properly make a SearchView with a drop down list?

Example:
Kc7xw.png
I want to make a searchView with a dropdown list.
There is a SearchDbAdapter class, written according to an article with habrahabr
. There is a virtual FTS table that contains two columns. The first column (KEY_INPUT) is a list of possible user queries. The second column (KEY_ANKER) is a list of html files with anchors corresponding to these queries.

public class SearchDbAdapter {
    private static final String DATABASE_NAME = "mhdb";
    private static final String FTS_VIRTUAL_TABLE = "srcht";
    private static final int DATABASE_VERSION = 1;
    public static final String KEY_INPUT = "rqst";
    public static final String KEY_ANKER = "ankr";

    private static final String DATABASE_CREATE = "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" + KEY_INPUT + "," + KEY_ANKER + ");";

    private final Context mCtx;

    // Массив с поисковыми запросами (темами и разделами, содержащимися в файлах)
    public static final String search_arr[] = {"data1","data2","data3",data4"};
    // Массив с соответствующими им html-файлами с якорями (файлы хранятся в папке assets проекта)
    public static final String ankers_arr[] = {"file1.html#an1","file2.html#an2","file1.html#an3","file1.html#an4"};

    private DatabaseHelper mDbHelper;
    private static SQLiteDatabase mDb;

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
            int LNGTH = search_arr.length;
            ContentValues initValues = new ContentValues();
            for(int i=0; i<LNGTH; i++){
                initValues.put(KEY_INPUT, search_arr[i]);
                initValues.put(KEY_ANKER, ankers_arr[i]);
                db.insert(FTS_VIRTUAL_TABLE, null, initValues);
                initValues.clear();
            }
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
            onCreate(db);
        }
    }

    public SearchDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public SearchDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        if (mDbHelper != null) {
            mDbHelper.close();
        }
    }

    //метод, возвращающий курсор с данными
    public static Cursor searchAnker(String inputText) throws SQLException {
        inputText = inputText.toLowerCase();
        String query = "SELECT docid as _id," + KEY_INPUT + "," + KEY_ANKER + " FROM " + FTS_VIRTUAL_TABLE + " WHERE " +  KEY_INPUT + " MATCH '" + inputText + "';";
        Cursor mCursor = mDb.rawQuery(query,null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
}

Working with SearchView is carried out as follows:
1. The search query "data2" is entered into SearchView. The SearchView listener calls the searchAnker() method of the SearchDbAdapter class, which returns a cursor (mCursor) containing queries similar to the entered text and html files with anchors corresponding to these queries: data2 request 3 - file1.html#an3 data2 request 4 - file2.html# an4
2. Similar requests contained in mCursor are displayed in the drop-down list: data2 request 3, data2 request 4.
3. When clicking on the elements of the drop-down list, an activity is launched, into which the corresponding html-file name with an anchor from mCursor: file1 is passed with the intent. html#an3
But I do not fully understand how to make this very drop-down list.
I also encountered another problem, for some reason searchAnker returns an empty cursor, I tried all the options that are in the KEY_INPUT column
In the onQueryTextChange method, I call searchAnker (query), which is passed the entered query text:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String text) {

            Toast toast = Toast.makeText(getApplicationContext(), "Text submit", Toast.LENGTH_SHORT);
            toast.show();

            return true;
        }

        @Override
        public boolean onQueryTextChange(String query) {

            try {
                cursor = sdb.searchAnker(query);

            } catch (SQLException e) {
                e.printStackTrace();
            }

            if(cursor.getCount() != 0)
            {
                // формируем столбцы сопоставления
                String[] from = new String[] { SearchDbAdapter.KEY_INPUT};
                int[] to = new int[] { R.id.search_result_text_view };

                // создааем адаптер и настраиваем список
                cursorAdapter = new SimpleCursorAdapter(MainActivity.this, R.layout.result_search_item, cursor, from, to, 0);

                searchView.setSuggestionsAdapter(cursorAdapter);

                return true;
            }
            else
            {
                return false;
            }
        }
    });

What am I doing wrong and how to properly implement this drop down list?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question