In the previous tutorial <add search function for Android Applications>, we learned how to search for the basic functions of the Framework in android applications. In this tutorial, you will continue to learn how to add the search tips and suggestions function to the search application.
What is search suggestion?
First, let's look at what is the search suggestion. In the Android app, when the user inputs a search string, the system will list the list containing the user input string in a drop-down Box Based on the part or whole of the input string, in this way, you can select from the drop-down list without entering all the characters. If this function can be added to the search module of the APP, it is undoubtedly very convenient for users. It is a diagram of the search recommendations used in the search APP:
Two recommended search modes
To enable the search application to support search recommendations, you must add a custom content provider to the application and set the search metadata in the configuration file.
Android supports two types of search suggestion modes:
· User input-based search recommendations
· Search recommendations based on the APP database, that is, extract data from the APP database for search recommendations
The following describes how to configure two search recommendations:
User input-based search recommendations
This method is relatively easy to use. In Android, The SearchRecentSuggestionsProvider class is provided to retrieve the content recently entered by the user. Developers only need to inherit the class, perform the following settings in the constructor:
- import android.content.SearchRecentSuggestionsProvider;
- publicclass SampleRecentSuggestionsProvider
- extends SearchRecentSuggestionsProvider {
- public static final String AUTHORITY =
- SampleRecentSuggestionsProvider.class.getName();
- public static final int MODE =DATABASE_MODE_QUERIES;
- public SampleRecentSuggestionsProvider() {
- setupSuggestions(AUTHORITY, MODE);
- }
- }
In the above class, the SearchRecentSuggestionsProvider is inherited and configured in the constructor. In this way, the custom contentprovider has the ability to query the user's recent input and retrieval.
However, the user's previous search input must be saved at the same time, so that the user can be re-displayed when the user inputs again. The following code must be written in the search activity:
- SearchRecentSuggestions suggestions =
- newSearchRecentSuggestions(this,
- SampleRecentSuggestionsProvider.AUTHORITY,
- SampleRecentSuggestionsProvider.MODE);
- suggestions.saveRecentQuery(query, null);
The code above shows that the SearchRecentSuggestionsProvider
The saveRecentQuery method saves search records.
Next, you must configure the contentprovider in the configuration file as follows:
- <provider
- android:authorities="de.openminds.SampleRecentSuggestionsProvider"
- android:name=".SampleRecentSuggestionsProvider">
- </provider>
Finally, configure searchable. xml as follows:
- <? xml version="1.0"encoding="utf-8"?>
- <searchablexmlns:androidsearchablexmlns:android="http://schemas.android.com/apk/res/android"
- android:label="@string/search_label"
- android:hint="@string/search_hint"
- android:searchSettingsDescription="@string/search_settings_description"
- android:searchSuggestAuthority="com.grokkingandroid.SampleRecentSuggestionsProvider "
- android:searchSuggestIntentAction="android.intent.action.SEARCH"
- android:searchSuggestThreshold="1"
- android:includeInGlobalSearch="true"
- android:searchSuggestSelection=" ?"
- >
- </searchable>
Some parameters are described as follows:
Android: searchSuggestAuthorith
The value of this attribute is AUTHORITH in SearchSuggestAuthorith.
Android: searchSuggestIntentAction
This attribute defines the target action that occurs when the content of the Search Prompt is selected.
Android: searchSuggestThreshold
A prompt is displayed only when the attribute defines at least a few characters are entered.
Android: includeInGlobalSearch
Whether to add content to android global search. True.
Android: searchSuggestSelection
Defines placeholders for parameters during search
Search records saved by databases in Android
SearchRecentSuggestionsProvider stores the most recent search records in suggestions. db. This db stores the id, query item, a displayed text, and the timestamp during the search. Note that this timestamp is required because all search records are sorted by time.
As a developer, you should consider regularly clearing search records or giving users the opportunity to manually clear search records so that users can see more search suggestion items on a regular basis from the search suggestion list. It is very easy to clear the recommended search records. You only need to call the clearHistory () method of the SearchRecentSuggestions object. By default, Android retains 250 search recommendations in the system.
Application-based search recommendations
In more cases, developers hope to provide users with the search function based on the app itself. In this way, users can provide users with search suggestions based on the content of the APP. In this case, in the Custom provider, you only need to pay attention to query () and getContentType.
First, you must obtain the content entered by the user in the search text box in the application, and then call the query () method to search for the app. The following two methods can be used to obtain the user input content:
· By default, the user's input content is obtained through URI.
· Query strings in the configuration file
First, let's take a look at how to obtain the user's input content through URI. The system will use the query () function to query in the Content Provider, and then use Cursor to return the corresponding suggestion. The system constructs user input into the following URI:
Content: // authority/optionalPath/SUGGEST_URI_PATH_QUERY/queryText
Note that the querytext at the end of the Uri is URL encoded, so you need to decode it.
It is generally obtained using the following method: Stringquery = uri. getLastPathSegment (). toLowerCase ();
Here optional. suggest. path is the android: searchSuggestPath set in the searchable configuration file. If it is not set in the searchable configuration file, optional. suggest. of course, path is not included in uri. You only need to set android: searchSuggestPath when you need a ContentProvider to provide suggestions queries for multiple searchable activities. In this case, it is used to identify the searchableactivities.
Note: SUGGEST_URI_PATH_QUERY is not a URI literal string. It is a static member constant, indicating that the value of this constant is added to the uri.
The following is the related usage code:
- Public Cursor query (Uri uri, String [] projection, String selection,
- String [] selectionArgs, String sortOrder ){
- String query = uri. getLastPathSegment ();
- If (SearchManager. SUGGEST_URI_PATH_QUERY.equals (query )){
- // If a record that matches the user input is found
- }
- Else {
- // If no record matching user input is found
- }
- }
Next, let's take a look at how to set the query string in the configuration file. You can add the android: searchSuggestSelection option in the configuration file as follows:
Android: searchSuggestSelection = "namelike? "
The query () method code is as follows:
- Public Cursor query (Uri uri, String [] projection, String selection,
- String [] selectionArgs, String sortOrder ){
- If (selectionArgs! = Null & selectionArgs. length> 0 & selectionArgs [0]. length ()> 0 ){
- // The user input is saved in selectionArgs [0 ].
- }
- Else {
- // The user did not enter any content
- }
- }
In addition, you can configure the recommended minimum number of characters in the configuration file. For example, android: searchSuggestThreshold = "3" indicates that after you enter at least three characters, to start calling the search suggestion.
Process returned results
The following describes how to handle the problem of returning the search suggestion to the front-end interface. First, in the configuration file, configure which action to use and which URI to use. This URI is actually the final data source list of the recommended item. The configuration is as follows:
Android: searchSuggestIntentAction = "Android. intent. action. VIEW" Android: searchSuggestIntentData = "Content: // someAuthority/somePath" |
The recommended items for returned search are returned in the form of a cursor. Each column must strictly abide by the relevant rules. The following lists several important columns:
Constant |
Usage |
SUGGEST_COLUMN_TEXT_1 |
Text to be displayed on the first line |
SUGGEST_COLUMN_TEXT_2 |
Text displayed on the second line |
SUGGEST_COLUMN_INTENT_DATA_ID |
Additional id added to data_uri |
Although only Searchmanager. SUGGEST_COLUMN_TEXT_1 is mandatory, the id option is also required to know which option is selected.
In addition, you also need to convert the searched data to the cursor data format, which requires a little conversion. This can be converted using the setprojectionMap method of SQLITEQueryBuilder. In the next tutorial, we will explain its usage in detail. The relevant code is listed here:
- Map<String, String> projectionMap = newHashMap<String, String>();
-
- projectionMap.put(COL_BAND, COL_BAND +" AS " + SearchManager.SUGGEST_COLUMN_TEXT_1);
-
- projectionMap.put(COL_ID, COL_ID);
-
- projectionMap.put(COL_ROW_ID,COL_ROW_ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
-
- projectionMap.put(COL_LOCATION,COL_LOCATION + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_2);
-
- projectionMap.put(COL_DATE, COL_DATE);
-
- builder.setProjectionMap(projectionMap);
Intent in response to user search
After you enter a search term, the Android search Framework calls the activity configured in the manifest file, which is implemented using an explicit intent. As far as the search suggestion for searching in the app is concerned, this intent will include the data in the configuration file and the data returned from the cursor.
The specific processing of the user's search response depends on whether the user uses the search suggestion based on the search term that the user has already entered or the search suggestion based on the APP's own data.
If you use a search suggestion based on the search term you have already entered, the intent action is Intent. ACTION_SEARCH, which is the same as that mentioned in the previous tutorial.
In most cases, users want to see the details of the data that is provided based on the APP data, expected to jump to see the details of the data, which can be set by Intent. ACTION_VIEW.
Because the searched activity generally inherits the ListActivity, you need to open another activity to view the specific content of a data item. The Code is as follows:
- private void handleIntent(Intentintent) {
-
- if(Intent.ACTION_SEARCH.equals(intent.getAction())) {
-
- String query =intent.getStringExtra(SearchManager.QUERY);
-
- doSearch(query);
-
- } else if(Intent.ACTION_VIEW.equals(intent.getAction())) {
-
- Uri detailUri =intent.getData();
-
- String id = detailUri.getLastPathSegment();
-
- Intent detailsIntent =new Intent(getApplicationContext(), DetailsActivity.class);
-
- detailsIntent.putExtra("ID", id);
-
- startActivity(detailsIntent);
-
- finish();
-
- }
-
- }
Global Search
For global search settings, you only need to make the following settings in the configuration file:
Android: includeInGlobalSearch = "true"
But the question is, how can I place your APP in the Android search list? For example:
Your APP itself cannot change these values, but Android provides
Android. app. SearchManager. INTENT_ACTION_GLOBAL_SEARCH
You can add your APP to the search list. In this way, you can search in the search list as shown in the following figure:
The biggest question about search recommendations
Note that the biggest problem with search recommendations is that it is difficult for developers to control styles, which is a big problem. Especially if the style recommended for search in the APP is different from other styles in the APP, the user experience will be affected.
In addition, if you want to display different data in the search recommendations, it may also become troublesome. For example, in a concert app, information about the location and band may appear. Developers attempt to clearly separate the information in the search recommendations so that users can choose easily, however, it is a pity that such a function cannot be implemented unless the developer conducts custom development.
Summary
In this tutorial, I will focus on how to add two search methods and notes to the APP. In the next tutorial, I will explain how to use search shortcuts, coming soon.
BKJIA translations are not permitted to be reprinted. For reposted by the media partners, please indicate the source, author, and BKJIA translator !]