Skip to content Skip to sidebar Skip to footer

Android: Get Text Of A Search Suggestion Clicked Item

I am using the officical Android sample code SearchableDictionary, that gives us a search interface, where you can search for a word and while the user types, suggestions are displ

Solution 1:

I think a security way to get the String query when the user click in a suggestion is by getting the QUERY from the intent android automatically pass when a search is made.

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // 1. Handle the intent on activity startuphandleIntent(getIntent());
}

/**
* This method is necessary if you set android:launchMode="singleTop"
* in your activity Manifest. See the explanation below about singleTop.
* @param query : string the user searched for.
*/@OverrideprotectedvoidonNewIntent(Intent intent) {
    setIntent(intent);
    handleIntent(intent);
}

privatevoidhandleIntent(Intent intent) {

    // ------------------------------------------------------//                     ANSWER IS HERE// ------------------------------------------------------if (Intent.ACTION_SEARCH.equals(intent.getAction())) {

        // This will get the String from the clicked suggestionString query = intent.getStringExtra(SearchManager.QUERY);
        displaySearchResults(query);
    }
}

/**
* 1. Dismiss the KeyBoard and the SearchView (searchMenuItem.collapseActionView();)
* 2. Switch the container to another fragment;
* 3. Send the query to this new fragment;
*/privatevoiddisplaySearchResults(String query) {
    dismissKeyBoardAndSearchView();

    // Open SearchShowFragment and display the resultsSearchShowFragment searchShowFragment = newSearchShowFragment();
    Bundle bundle = newBundle();
    bundle.putString(SearchShowFragment.QUERY, query);
    searchShowFragment.setArguments(bundle);
    switchToFragment(searchShowFragment);
}

It is recomended to set singleTop in your activity manifest. Because, if the user make several searches, one followed by the other, it will prevent the system to create the activity several times, one in the top of the other. Imagine the user make 10 searches and then he start to press the back button, it would go back through all the 10 disturbing steps to reach the start.

<activityandroid:name=".MainActivity"android:launchMode="singleTop"><intent-filter><actionandroid:name="android.intent.action.MAIN" /><actionandroid:name="android.intent.action.SEARCH" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter><meta-dataandroid:name="android.app.searchable"android:resource="@xml/searchable" /></activity>

OBSERVATIONS: I am using a single Activity (MainActivity) and two Fragments, the first fragment display all the items and the second fragment display the items by using the query search. The logic to handle the query, the intent, searchview and so on is all made in the MainActivity and the fragments only receives the query and perform the search.

HOW TO HANDLE THE INTENT WHEN THE USER TYPE IT

Note that this will take care only when the user clicks in a suggestions, this will not work when the user type a word and press enter.

For that, use the method below in your onCreateOptionsMenu().

@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
    // Inflates the options menu from XMLMenuInflaterinflater= getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    // Get the SearchView and set the searchable configurationfinalSearchManagersearchManager= (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchMenuItem = menu.findItem(R.id.menu_search);
    searchView = (SearchView) searchMenuItem.getActionView();
    // Assumes the current activity is the searchable activity
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setQueryRefinementEnabled(true);

    // -----------------------------------------------------------------------//                             Typing a Query// -----------------------------------------------------------------------
    searchView.setOnQueryTextListener(newSearchView.OnQueryTextListener() {
        @OverridepublicbooleanonQueryTextSubmit(String query) {

            // Save the query to display recent queriesSearchRecentSuggestionssuggestions=newSearchRecentSuggestions(MainActivity.this,
                    MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
            suggestions.saveRecentQuery(query, null);
            // To protect the user's privacy you should always provide a way to clear his search history.// Put in the menu a way that he can clear the history with the following line below./*suggestions.clearHistory();*/// Display the results
            displaySearchResults(query);

            returntrue;
        }

        @OverridepublicbooleanonQueryTextChange(String newText) {
            returnfalse;
        }
    });

    returnsuper.onCreateOptionsMenu(menu);
}

Happy coding!

This is from the official google documentation: Creating a Search Interface

Post a Comment for "Android: Get Text Of A Search Suggestion Clicked Item"