danada danada - 4 months ago 16
Android Question

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

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

, but this doesn't seem to work with a search widget.

  • Override in question:

    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
is always


is called, but the bundle does not make it to my

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


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.

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


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

mValue = intent.getStringExtra("KEY");