Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

preface

Recently, a client wanted to implement the search history function in the search. In fact, this function sounds very simple, but in fact, there are a lot of logic in it. When I wrote it at the beginning, I was foggy, and when I finally proposed it to the client, I would like to sort it out in detail and share my thoughts

The main logic

  1. Save current content after search
  2. Record the most recent search first
  3. Search history can be clicked to perform the search function and brought to the front

I used ObjectBox as the data storage, because the actual project uses Java, so there is no Room, and it seems that the first search for Room will take at least 200ms, but you can start it randomly in an activity. GreenDao is a little cumbersome to use, there is no need to query conditions, directly use ObjectBox, and super easy to use

Code

ObjectBox utility class

public class ObjectBoxUtils { public static BoxStore init() { BoxStore boxStore = null; try { boxStore = MyApplication.getBoxStore(); if (boxStore == null) { boxStore = MyObjectBox.builder().androidContext(MyApplication.applicationContext).build(); MyApplication.setBoxStore(boxStore); } } catch (Exception e) { } return boxStore; } public static <T> List<T> getAllData(Class clazz) { try { BoxStore boxStore = init(); if (boxStore ! = null && ! boxStore.isClosed()) { Box<T> box = boxStore.boxFor(clazz); return box.getAll(); } } catch (Exception e) { } return new ArrayList<>(); } public static <T> long addData(T o, Class c) {try {BoxStore BoxStore = init(); if (boxStore ! = null && ! boxStore.isClosed()) { return boxStore.boxFor(c).put(o); } } catch (Throwable e) { } return 0; } public static HistoryBean getHistroyBean(String name) { try { BoxStore boxStore = init(); if (boxStore ! = null && ! boxStore.isClosed()) { Box<HistoryBean> box = boxStore.boxFor(HistoryBean.class); HistoryBean first = box.query().equal(HistoryBean_.name, name).build().findFirst(); return first; } } catch (Exception e) { } return null; }}Copy the code

In fact, I initialized the ObjectBox in Application, but in actual projects, sometimes the initialization fails, resulting in a direct null pointer, so every time I call, I will check whether the initialization is done, if not, I will do the corresponding operation

Activity

class HistoryActivity : AppCompatActivity() { private var list: MutableList<HistoryBean>? = null private var inflate: ActivityHistoryBinding? = null private var historyAdapter: HistoryAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) inflate = ActivityHistoryBinding.inflate(layoutInflater) setContentView(inflate? .root) list = ObjectBoxUtils.getAllData(HistoryBean::class.java) list? .sort() inflate!! .rv.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false) historyAdapter = HistoryAdapter(this, list) inflate!! .rv.adapter = historyAdapter inflate!! .et.setOnEditorActionListener(object : TextView.OnEditorActionListener { override fun onEditorAction(v: TextView? , actionId: Int, event: KeyEvent?) : Boolean { saveHistory(inflate!! .et.text.toString()) return true}})} /** * Save search history ** / fun saveHistory(keyWord: String) {// Check whether there is local data in the name parameter var histroyBean: HistoryBean? = ObjectBoxUtils. GetHistroyBean (keyWord) val currentTimeMillis = System. CurrentTimeMillis () / / not just newly created an if (histroyBean == null) { histroyBean = HistoryBean(currentTimeMillis, keyWord, CurrentTimeMillis)} else {// If there is one, update the time HistroyBean. SetTime (currentTimeMillis)} // Save new/old data to local objectBoxutils. addData(histroyBean, HistoryBean::class.java) // Every operation retrieves data from the database, with very low performance consumption. .clear() list? AddAll (ObjectBoxUtils. GetAllData (HistoryBean: : class. Java)) / / entity Bean rewrote the Comparable to sort the list? .sort() historyAdapter? .notifyDataSetChanged() } }Copy the code

The corresponding comments are all in the code. To be honest, Kotlin is very uncomfortable to use it. It is because of his poor grammar

Entity class

@Entity public class HistoryBean implements Comparable<HistoryBean> { @Id(assignable = true) public long id; public HistoryBean(long id, String name, long time) { this.id = id; this.name = name; this.time = time; } public String name; public long time; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } @Override public int compareTo(HistoryBean o) { return (int) (o.time-time); }}Copy the code

The entity class overwrites CompareTo. Because the collection's sort actually calls the ComparteTo, we can simplify a lot of the business layer by overwriting the corresponding logic

The effect

Well, the effect is good, continue to learn a painful custom View to go