-->

Best Practices for Handling Search

2019-04-04 17:09发布

问题:

I've got a SearchView setup, and I have a loosely decoupled architecture using Retrofit and Otto.

I am wondering what the Best Practices are for Search in Android, or any mobile application in general (meaning something like this could be applied to iOS as well).

Specifically I am using an AutoCompleteTextView to handle suggestions in my SearchView and the data is coming straight from the API. I don't believe this is a best practice since everytime a user changes text in the SearchView there is an API call initiated.

I'm thinking about storing a Cache in SQLite and then pinging results from there, but what if the user wants the most immediate data? How would you handle that? What pattern would that employ?

Would appreciate any thoughts on the best architecture or approach to Search in Android.

回答1:

I think there is no sense to make an API call before user stopped typing. So, you can put a delay, say, 500ms. When user stops typing, after 500ms you make an API call and show the results.

You can use a Handler's postDelayed method for scheduling search API calls. You can use Handler to control the message queue. You post a delayed Runnable each time user types a character and cancel previous messages. It will look this way:

public void onTextChanged(CharSequence s, int start, int before, int count) {
    handler.removeCallbacks(searchRunnable);
    handler.postDelayed(searchRunnable, 500);
}


回答2:

  • first you have to make the column as index which is search attribute.
  • you have to store only that column on sqlite database.Its used to select options from your table when search is made by users.
  • then you call api for search result, after the word selected in search bar.


回答3:

So to answer this question in a sufficient way, as I was not satisfied with the other answers here there are a few more steps to consider in this problem.

First we would need to ask a few questions in regards to how we would tackle this issue:

  • Is there autocomplete?
  • What is the scope of the search?
  • Would there be caching?

And many more questions.

I would probably first build a custom adapter to handle the querying in the search, then implement aggressive caching on the user's queries. This is important in the sense that a user's queries are very important. It would probably make sense to only used cached results for Autocomplete it is very expensive to implement autocomplete and have it ping the server at every text change.

Caching can be accomplished by using the SQLite helpers in Android. This can be expensive, but we are dealing with simple query objects, (as this should be the case from the API the objects should be memory or byte size expensive).