安卓:提供最近的搜索建议没有搜索活动?最近、建议

2023-09-12 22:35:13 作者:煮酒慰风尘

我有一个动作条搜索查看,我成功地能够与它进行搜索。 Android的文档没有解释如何实现搜索建议。我不希望有一个可搜索的活动。

I have an ActionBar SearchView and I am successfully able to make searches with it. The android documentation does not explain how to implement search suggestions. I do not want to have a searchable activity.

这是我的搜索code:

This is my search code:

public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_add_song, menu);
        final SearchView searchView = (SearchView) menu.findItem(R.id.song_search).getActionView();
        searchView.setFocusable(true);
        searchView.setIconified(false);
        final AddSongActivity activity = this;
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                // Do nothing
                return true;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                // Clear SearchView
                searchView.clearFocus();
                // Begin Spotify Search
                TextView notice = (TextView)findViewById(R.id.search_notice);
                URL url;
                try {
                    url = new URL("http://ws.spotify.com/search/1/track.json?q=" + URLEncoder.encode(query,"UTF-8"));
                } catch (MalformedURLException e) {
                    notice.setText("Malformed Search");
                    notice.setHeight(noticeHeight);
                    return true;
                } catch (UnsupportedEncodingException e) {
                    notice.setText("Unsupported Encoding. Maybe a problem with your device.");
                    notice.setHeight(noticeHeight);
                    return true;
                }
                new SearchDownload(url, activity).execute();
                notice.setText("Loading Tracks");
                notice.setHeight(noticeHeight);
                Log.i("infodb","" + noticeHeight);
                return true;
            }
        });

这适用于搜索,但我不知道要执行最近的搜索查询建议。我该如何去这样做?

This works for searching but I have no idea to implement recent search query suggestions. How do I go about doing this?

感谢你。

推荐答案

好吧,我花了我的时间这一点。我做我自己的简单的实施意见,从 SQLiteDatabase

Ok, I spent my time for this. I make my own simple suggestion implementation from SQLiteDatabase.

我们将创建3类,如以下

We will create 3 classes like the following

MainActivity - 用于测试搜索查看从数据库的建议 SuggestionDatabase - 这将存储您的最近搜索关键字 SuggestionSimpleCursorAdapter - 这是 SimpleCursorAdapter 的子类。我会解释为什么我让使用 SimpleCursorAdapter 这个类来代替。 MainActivity - for test of SearchView suggestion from database SuggestionDatabase - this will store your recent search keyword. SuggestionSimpleCursorAdapter - this is a subclass of SimpleCursorAdapter. I'll explain why I make this class instead of using SimpleCursorAdapter.

在codeS

// MainActivity.java

public class MainActivity 
    extends Activity
    implements SearchView.OnQueryTextListener,
                SearchView.OnSuggestionListener
{

    private SuggestionsDatabase database;
    private SearchView searchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        database = new SuggestionsDatabase(this);
        searchView = (SearchView) findViewById(R.id.searchView1);
        searchView.setOnQueryTextListener(this); 
        searchView.setOnSuggestionListener(this);
    }

    @Override
    public boolean onSuggestionSelect(int position) {

        return false;
    }

    @Override
    public boolean onSuggestionClick(int position) {

        SQLiteCursor cursor = (SQLiteCursor) searchView.getSuggestionsAdapter().getItem(position);
        int indexColumnSuggestion = cursor.getColumnIndex( SuggestionsDatabase.FIELD_SUGGESTION);

        searchView.setQuery(cursor.getString(indexColumnSuggestion), false);

        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        long result = database.insertSuggestion(query);
        return result != -1;
    }

    @Override
    public boolean onQueryTextChange(String newText) {

        Cursor cursor = database.getSuggestions(newText);
        if(cursor.getCount() != 0)
        {
            String[] columns = new String[] {SuggestionsDatabase.FIELD_SUGGESTION };
            int[] columnTextId = new int[] { android.R.id.text1};

            SuggestionSimpleCursorAdapter simple = new SuggestionSimpleCursorAdapter(getBaseContext(),
                    android.R.layout.simple_list_item_1, cursor,
                    columns , columnTextId
                    , 0);

            searchView.setSuggestionsAdapter(simple);
            return true;
        }
        else
        {
            return false;
        }
    }

}

工作原理

当用户点击搜索按钮,在 onQueryTextSubmit()将被触发,然后搜索关键词将被保存在我们的数据库。比方说,我们提交一个关键词你好 如果用户在写一个字符串,例如赫尔或H搜索查看 onQueryTextChange()将被调用,然后我们搜索这个关键字 SQLiteDatabase SuggestionDatabase )。如果赫尔或H匹配你好,通过设置返回光标在 SuggestionSimpleCursorAdapter 显示的查询结果,然后将该适配器搜索查看。这里的图片。 When user taps the search button, the onQueryTextSubmit() will be triggered and then the search keyword will be saved in our database. Let's say we submit a keyword "Hello" If the user writes a string for example "Hel" or "H" in SearchView the onQueryTextChange() will be called and then we search this keyword in SQLiteDatabase (SuggestionDatabase). If "Hel" or "H" matches "Hello" , display the results of query by setting the returned Cursor in SuggestionSimpleCursorAdapter and then set this adapter in SearchView. Here's the picture.

3. Ofcourse,我们将利用这就是你好, onSuggestionClick(INT位置)将被要求的建议。我们从搜索查看的适配器 SQLiteCursor 对象( SuggestionSimpleCursorAdapter ),并从它那里得到的建议文本,设置的建议文本搜索查看对象

3. Ofcourse we will tap the suggestion which is "Hello", onSuggestionClick(int position) will be called for that. We get the SQLiteCursor object from the SearchView's adapter (SuggestionSimpleCursorAdapter) and get the Suggestion text from it, set the suggestion text in SearchView object

SQLiteCursor cursor = (SQLiteCursor) searchView.getSuggestionsAdapter().getItem(position);
int indexColumnSuggestion = cursor.getColumnIndex( SuggestionsDatabase.FIELD_SUGGESTION);
searchView.setQuery(cursor.getString(indexColumnSuggestion), false);

如果我们使用 SimpleCursorAdapter 这也工作正常,但让我们说我们有这个场景

If we use SimpleCursorAdapter it also works properly but let's say we have this scenario

如果我们在智能手机上运行这个程序,然后键入关键字赫尔,建议将正确显示。

如果我们旋转景观的屏幕?它会切换在全屏模式下,你仍然可以键入关键字。

将建议发生什么情况?让我们一起来看看。

What will happen in suggestion? Let's take a look.

请参阅怪异的建议吗?如何解决?通过覆盖 convertToString(光标光标)返回一个的CharSequence

See the weird suggestion? How we solve that? By overriding the convertToString(Cursor cursor) which returns a CharSequence

 // SuggestionSimpleCursorAdapter.java
public class SuggestionSimpleCursorAdapter
    extends SimpleCursorAdapter
{

    public SuggestionSimpleCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
    }

    public SuggestionSimpleCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
    }

    @Override
    public CharSequence convertToString(Cursor cursor) {

        int indexColumnSuggestion = cursor.getColumnIndex(SuggestionsDatabase.FIELD_SUGGESTION);

        return cursor.getString(indexColumnSuggestion);
    }


}

通过覆盖 convertToString(光标光标),这里的结果

和这里的数据库

// SuggestionDatabase.java
public class SuggestionsDatabase {

  public static final String DB_SUGGESTION = "SUGGESTION_DB";
  public final static String TABLE_SUGGESTION = "SUGGESTION_TB";
  public final static String FIELD_ID = "_id";
  public final static String FIELD_SUGGESTION = "suggestion";

  private SQLiteDatabase db;
  private Helper helper;

  public SuggestionsDatabase(Context context) {

    helper = new Helper(context, DB_SUGGESTION, null, 1);
    db = helper.getWritableDatabase();
  }

  public long insertSuggestion(String text)
  {
    ContentValues values = new ContentValues();
    values.put(FIELD_SUGGESTION, text);
    return db.insert(TABLE_SUGGESTION, null, values);
  }

  public Cursor getSuggestions(String text)
  {
    return db.query(TABLE_SUGGESTION, new String[] {FIELD_ID, FIELD_SUGGESTION}, 
            FIELD_SUGGESTION+" LIKE '"+ text +"%'", null, null, null, null);
  }


    private class Helper extends SQLiteOpenHelper
    {

    public Helper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE "+TABLE_SUGGESTION+" ("+
                    FIELD_ID+" integer primary key autoincrement, "+FIELD_SUGGESTION+" text);");
        Log.d("SUGGESTION", "DB CREATED");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

  }

}

我希望这个答案是非常有用的其他程序员很多。 :)

I hope this answer is useful to other programmers alot. :)