Nacho
Nacho

Reputation: 2057

Persist query in SearchView after resuming activity

I have an Activity with a ListView and clickeable items to show details of each of them in a separate Activity. My main activity has a SearchView to filter those items. I want to be able to click on an item (that open's a new activity) and when i press back button, my searchView remains same (with my filtered list).

I implemented my searchview like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    // Inflate menu to add items to action bar if it is present.
    inflater.inflate(R.menu.menu_main, menu);
    final MenuItem searchItem = menu.findItem(R.id.action_search);
    mSearchView = (SearchView) searchItem.getActionView();
    mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Log.w("SEARCH", "SearchOnQueryTextSubmit: " + query);
            mQuery = query;
            if (!mSearchView.isIconified()) {
                mSearchView.setIconified(true);
            }
            searchItem.collapseActionView();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            Log.w("SEARCH", "SearchOnQueryTextChanged: " + s);
            mQuery = s;
            contactAdapter.getFilter().filter(s);

            return false;
        }
    });

And i was trying to implement something into onResume or on the same onCreateOptionsMenu to check if mQuery had something.

if (!TextUtils.isEmpty(mQuery)) {
        final String thisQuery = mQuery;
        mSearchView.post(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "onResume: setting mQuery to searchView");
                Log.d(TAG, "mQuery: "+thisQuery);
                MenuItemCompat.expandActionView(searchItem);
                mSearchView.setQuery(thisQuery, true);
            }
        });
    }

Tried on both methods but with no success. On onCreateOptionsMenu, if i debugg it, SearchView is called with my query to be filtered, but right after that, another call comes with an empty search! I don't know where this comes from.

Any help? Thanks!

Upvotes: 1

Views: 679

Answers (1)

ishmaelMakitla
ishmaelMakitla

Reputation: 3812

I am glad this could help:

What you need is How to maintain the previous state of an activity. Check the selected answer here -

Upvotes: 1

Related Questions