Add search function for Android apps: add search recommendations

Source: Internet
Author: User

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:

 
 
  1. import android.content.SearchRecentSuggestionsProvider; 
  2. publicclass SampleRecentSuggestionsProvider 
  3. extends SearchRecentSuggestionsProvider { 
  4. public static final String AUTHORITY = 
  5. SampleRecentSuggestionsProvider.class.getName(); 
  6. public static final int MODE =DATABASE_MODE_QUERIES; 
  7. public SampleRecentSuggestionsProvider() { 
  8. 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:

 
 
  1. SearchRecentSuggestions suggestions = 
  2. newSearchRecentSuggestions(this, 
  3. SampleRecentSuggestionsProvider.AUTHORITY, 
  4. SampleRecentSuggestionsProvider.MODE); 
  5. 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:

 
 
  1. <provider 
  2. android:authorities="de.openminds.SampleRecentSuggestionsProvider" 
  3. android:name=".SampleRecentSuggestionsProvider"> 
  4. </provider> 

Finally, configure searchable. xml as follows:

 
 
  1. <? xml version="1.0"encoding="utf-8"?> 
  2. <searchablexmlns:androidsearchablexmlns:android="http://schemas.android.com/apk/res/android" 
  3. android:label="@string/search_label" 
  4. android:hint="@string/search_hint" 
  5. android:searchSettingsDescription="@string/search_settings_description" 
  6. android:searchSuggestAuthority="com.grokkingandroid.SampleRecentSuggestionsProvider " 
  7. android:searchSuggestIntentAction="android.intent.action.SEARCH" 
  8. android:searchSuggestThreshold="1" 
  9. android:includeInGlobalSearch="true" 
  10. android:searchSuggestSelection=" ?" 
  11. </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:

 
 
  1. Public Cursor query (Uri uri, String [] projection, String selection,
  2. String [] selectionArgs, String sortOrder ){
  3. String query = uri. getLastPathSegment ();
  4. If (SearchManager. SUGGEST_URI_PATH_QUERY.equals (query )){
  5. // If a record that matches the user input is found
  6. }
  7. Else {
  8. // If no record matching user input is found
  9. }
  10. }

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:

 
 
  1. Public Cursor query (Uri uri, String [] projection, String selection,
  2. String [] selectionArgs, String sortOrder ){
  3. If (selectionArgs! = Null & selectionArgs. length> 0 & selectionArgs [0]. length ()> 0 ){
  4. // The user input is saved in selectionArgs [0 ].
  5. }
  6. Else {
  7. // The user did not enter any content
  8. }
  9. }

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:

 
 
  1. Map<String, String> projectionMap = newHashMap<String, String>(); 
  2.  
  3. projectionMap.put(COL_BAND, COL_BAND +" AS " + SearchManager.SUGGEST_COLUMN_TEXT_1); 
  4.  
  5. projectionMap.put(COL_ID, COL_ID); 
  6.  
  7. projectionMap.put(COL_ROW_ID,COL_ROW_ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); 
  8.  
  9. projectionMap.put(COL_LOCATION,COL_LOCATION + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_2); 
  10.  
  11. projectionMap.put(COL_DATE, COL_DATE); 
  12.  
  13. 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:

 
 
  1. private void handleIntent(Intentintent) { 
  2.  
  3. if(Intent.ACTION_SEARCH.equals(intent.getAction())) { 
  4.  
  5. String query =intent.getStringExtra(SearchManager.QUERY); 
  6.  
  7. doSearch(query); 
  8.  
  9. } else if(Intent.ACTION_VIEW.equals(intent.getAction())) { 
  10.  
  11. Uri detailUri =intent.getData(); 
  12.  
  13. String id = detailUri.getLastPathSegment(); 
  14.  
  15. Intent detailsIntent =new Intent(getApplicationContext(), DetailsActivity.class); 
  16.  
  17. detailsIntent.putExtra("ID", id); 
  18.  
  19. startActivity(detailsIntent); 
  20.  
  21. finish(); 
  22.  
  23.  

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 !]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.