如何将“最近”查询添加到另一个活动



我正在创建可搜索的词典,我想显示用户在 SearchView 中对其他活动所做的最新查询。 就像安卓词典中的"最近"选项一样。

private void handleIntent(Intent inent) {
 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        // handles a click on a search suggestion; launches activity to show word
        Intent wordIntent = new Intent(this, WordActivity.class);
        wordIntent.setData(intent.getData());
        startActivity(wordIntent);
        finish();
    } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        // handles a search query
        String query = intent.getStringExtra(SearchManager.QUERY);
        SearchRecentSuggestions suggestions=new SearchRecentSuggestions(this, MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
        suggestions.saveRecentQuery(query, null);
        showResults(query);
    }
}

ShowResult 显示搜索活动中的查询建议,我想将最近的查询显示到其他活动中,我该怎么做?

也许这段代码将帮助您 共享首选项 .

SharedPreferences sPreferences = getSharedPreferences("tushar", Context.MODE_PRIVATE);
Editor sEditor = sPreferences.edit();
Set<String> setName = new HashSet<String>();
setName.add("tushar");
setName.add("pandey");
setName.add("Ram");
setName.add("Shiva");
sEditor.putStringSet("ko", setName);
sEditor.commit() ;
Log.i("hello","tushar:pandey") ;
Set<String> setName_ = sPreferences.getStringSet("tushar", setName);
Log.i(setName_.toString(),"tushar:pandey") ;

可以通过 ContentResolver 访问保存的查询:

ContentResolver contentResolver = getApplicationContext().getContentResolver();
String contentUri = "content://" + MySuggestionProvider.AUTHORITY + '/' + SearchManager.SUGGEST_URI_PATH_QUERY;
Uri uri = Uri.parse(uriStr);
Cursor cursor = contentResolver.query(uri, null, null, new String[] { null }, null);

现在,使用收到的光标填充列表视图。使用 showResults() 代码创建另一个活动。

最新更新