Passing Extra Variables to Search Activity Invoked by a Search Widget

Implementing a search activity into your android application can be quite a breeze. If you're working with search in an ActionBar, the framework usually handles the load of the code- all you have to do is define your search menu item in the ActionBar. This simplification comes with some issues though.

The problem

Often while implementing a search, we want to pass contextual data along with our query. This is actually covered in the Creating a Search Interface article on the Android Developers site, but the code provided does not work with a SearchWidget. Traditionally, we would override the onSearchRequested method, but since the SearchWidget dispatches the search intent, we don't really have a way to intercept the intent and pass additional data.

Android search

The solution

To solve this problem we have to think a little about how the android application flow actually works. Almost every navigational activity or action performed shoots off an intent which is handled either somewhere in your application's code, or by one of the applications you have installed that can handle the type of intent started. Our SearchWidget does exactly that- It sends an intent to our search activity which handles our query.

Thankfully we can override the startActivity method which is called when our current activity starts another activity. Our code is pretty straightforward and involves checking the intent's action to make sure it's a search action.

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


You can see that after the code confirms the action, we add an extra to the intent before the super method is called. Simple solution to a simple problem.

Android logo