To restore SearchView state

When you want to restore searchView state, we should use onSaveInstanceState(Bundle outState). Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

Complete code in github

There is a example how to work this important method in our Activity.

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
    private SearchView mSearchView;
    private String mSearchString;
    private static final String SEARCH_KEY = "search";
    protected void onCreate(Bundle savedInstanceState) {
        // if you saved something on outState you can recover them here
        if (savedInstanceState != null) {
            mSearchString = savedInstanceState.getString(SEARCH_KEY);
    // This is called before the activity is destroyed
    protected void onSaveInstanceState(Bundle outState) {
        mSearchString = mSearchView.getQuery().toString();
        outState.putString(SEARCH_KEY, mSearchString);
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(, menu);
        MenuItem searchMenuItem = menu.findItem(;
        mSearchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
        //focus the SearchView
        if (mSearchString != null && !mSearchString.isEmpty()) {
            mSearchView.setQuery(mSearchString, true);
        return super.onCreateOptionsMenu(menu);

Now we create our SearchView. First we need to create new folder which name is menu.

After that we create new xml file, which name is “main”.

After that we create new xml file, which name is “main”.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""
        app:showAsAction="always|collapseActionView" />

Finally our string file.

    <string name="app_name">"CustomSearchView "</string>
    <string name="activity_main_text"></string>
    <string name="menu_main_search_title">Search</string>

Complete code in github

One thought on “To restore SearchView state

Leave a Reply

Your email address will not be published. Required fields are marked *