How do I pass extra variables during a search invoked by a SearchView/ Widget?

倖福魔咒の 提交于 2020-01-12 06:53:59

问题


I am successfully using a search widget in my action bar to perform a search following this guide. The search is fine, but I'm wondering how to pass additional variables on a search. The same guide states I can override onSearchRequested(), but this doesn't seem to work with a search widget.

  • Override in question:

    @Override
    public boolean onSearchRequested() {    
        Bundle appData = new Bundle();
        appData.putString("KEY", "VALUE");
        startSearch(null, false, appData, false);
        return true;
    }
    
  • Getting the bundle in my activity class:

    protected void onCreate(Bundle savedInstanceState) {
        // ...
        Intent intent = getIntent();
        Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
        String value = appData.getString("KEY");
        Log.d("VALUE", value);
        // ...
    }
    

My application crashes upon creating the search class because appData is always null.

Note

onSearchRequested() is called, but the bundle does not make it to my onCreate() method.

All extras from the passed intent are {user_query=my-query, query=my-query}.


回答1:


It seems the only way to do this is to intercept new activities created in your activity which is search-enabled. To do this we override the startActivity() method. We can then check to make sure the activity is indeed the search activity, then add an extra to the intent. The working code is below.

@Override
public void startActivity(Intent intent) {      
    // check if search intent
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        intent.putExtra("KEY", "VALUE");
    }

    super.startActivity(intent);
}

You can then grab your extra as you would any other extra in your search activity using:

mValue = intent.getStringExtra("KEY");



回答2:


You can override the onSearchRequested method inside the Activity that's invoking the search.

@Override
public boolean onSearchRequested() {
     Bundle appData = new Bundle();
     appData.putBoolean(SearchableActivity.JARGON, true);
     startSearch(null, false, appData, false);
     return true;
 }

then you can extract this data inside the SearchableActivity

Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
    boolean jargon = appData.getBoolean(SearchableActivity.JARGON);
}



回答3:


I think you want to just use

String value = intent.getStringExtra(SearchManager.APP_DATA);

because the intent holds the bundle you passed to start the search.



来源:https://stackoverflow.com/questions/14597229/how-do-i-pass-extra-variables-during-a-search-invoked-by-a-searchview-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!