Nitin Misra
Nitin Misra

Reputation: 4522

Pass ActionBar search query to fragment

Here is the seen I have a SHERLOCK FRAGMENT ACTIVITY which holds four FRAGMENTS and a SEARCH VIEW. There are 4 fragments in which last is FRAGMENT SEARCH RESULTS

My question is how to pass data of search query to FRAGMENT SEARCH RESULTS from search view and display search result in FRAGMENT SEARCH RESULTS

I implemented this

private void setupSearchView(MenuItem searchItem) {
        if (isAlwaysExpanded()) {
            mSearchView.setIconifiedByDefault(false);
        } else {
            searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        }
        mSearchView.setOnQueryTextListener(this);
    }

    public boolean onClose() {
        return false;
    }

    protected boolean isAlwaysExpanded() {
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        if (query.length() > 0) {
            **//WHAT SHOULD I WRITE HERE**
        }
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }

Upvotes: 5

Views: 8099

Answers (3)

S. Alawadi
S. Alawadi

Reputation: 144

i found a workaround you can override this method (startActivity(Intent) ) in your BaseActivity and then check if the action is ACTION_SEARCH then do your special job

@Override
    public void startActivity(Intent intent) {
        try {
            if (intent.getAction().equals(Intent.ACTION_SEARCH))
                // Do ur job here start fragment for Example

             return;
        } catch (Exception e) {

        }
        super.startActivity(intent);
    }

Upvotes: 0

Nitin Misra
Nitin Misra

Reputation: 4522

@Override
    public boolean onQueryTextSubmit(String query) {
        if (query.length() > 0) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            Fragment newFragment = new SearchFragment(); //your search fragment
            Bundle args = new Bundle();
            args.putString("query_string", query);
            newFragment.setArguments(args);

            transaction.replace(R.id.content_frame, newFragment);
            transaction.addToBackStack(null);
            transaction.commit();   
        }
        return false;
    }

Upvotes: 1

Pradip
Pradip

Reputation: 3177

A good example in here action-bar-search-view.

To display search result, you need to pass submitYourQuery(query); and return true on successful search.

The process of storing and searching your data is unique to your application. You can store and search your data in many ways. Storing and searching your data is something you should carefully consider in terms of your needs and your data format.

Get the more details from the android documentation ReceivingTheQuery

Upvotes: 1

Related Questions