In-app Search function implementation
– Android TV app hands on Tutorial 13

Search function implementation

The usage of SearchFragment of Leanback support library and UI related implementation are explained in previous chapter. In this chapter, I will explain (background) search function logic.

Most of the implementation in this chapter is just a explanation of googlesamples.

In-app search algorithm

Search algorithm is implemented in loadRows method, especially the main logic is in doInBackground method of AsyncTask. It is actually simple, just checking the string “query” is contained in either title or description of Movie items.

The UI related task Adapter handling is done in UI thread. onPreExecute initializes mRowsAdapter, which will contain the search results, by clear method. Searching itself is executed in background thread in doInBackground, and it makes new ListRow which contains the search results. This listRow is added to Adapter in UI thread by onPostExecute method. 

Execute search

Since search algorithm is already implemented above, we only need to call this function to get search results.

Call loadRows method in onQueryTextSubmit method. Easy implementation is already done! let’s try build and run the code here.

search2_1-2015-09-03-201043

Search function works correctly.

We have already finished minimum implementation for search function. Next step is to enable search even during the user’s text typing.

Dynamic search execution

To detect when user typing search query, we can use onQueryTextChange method. So basic concept is to just execute loadRows method in onQueryTextChange to implement dynamic (during user input) search. However, onQueryTextChange will be executed every time user input one words, and we should not call loadRows method when it has already executed. Here, Handler is used to manage executing loadRows method.

loadQueryWithDelay method uses Handler to post loadRows task with a little delay so that loadRows task is not executed too frequently. The last modification is to call this loadQueryWithDelay method from onQueryTextChange.

 Build and run

As can be seen by video, search has executed even during the user is typing search query.

Source code is on github.

 

 

Sponsored Links

One response

Leave a Reply

Your email address will not be published.