//保存搜索历史,保存到SharedPreferences
const val PREFERENCE_NAME = "save_city_search_history"
const val SEARCH_HISTORY = "search_city_search_history"
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
fun saveSearchHistory(mContext: Context, saveString: String) {
val sp: SharedPreferences = mContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
if (saveString == "") {
return
} else {
val history: String = sp.getString(SEARCH_HISTORY, "")
val historyList: ArrayList<String> = arrayListOf()
val historyListSpit = history.split(",")
for (index in historyListSpit) {
historyList.add(index)
historyList.remove("")
}
if (historyList.size == 1 && historyList[0] == "") {
historyList.clear()
}
val edit = sp.edit()
if (historyList.isNotEmpty()) {
for (index in historyList) {
if (saveString == index) {
historyList.remove(index)
break
}
}
historyList.add(0, saveString)
//如果超过6,删除最后一个
if (historyList.size > 6)
historyList.removeAt(historyList.size - 1)
val sb: StringBuilder = StringBuilder()
for (index in historyList) {
sb.append("${index},")
}
edit.putString(SEARCH_HISTORY, sb.toString())
edit.commit()
} else {
edit.putString(SEARCH_HISTORY, "${saveString},")
edit.commit()
}
}
}
//获取搜索历史
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
fun getSearchHistory(mContext: Context): ArrayList<String> {
val sp: SharedPreferences = mContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
val history: String = sp.getString(SEARCH_HISTORY, "")
var historyList: ArrayList<String> = arrayListOf()
val historyListSpit = history.split(",")
for (index in historyListSpit) {
historyList.add(index)
historyList.remove("")
}
if (historyList.size == 1 && historyList[0] == "") {
historyList.clear()
}
return historyList
}
Android搜索历史本地保存
最新推荐文章于 2024-04-01 12:04:55 发布
本文介绍了一种在Android应用中使用SharedPreferences保存和读取搜索历史记录的方法。通过将历史记录字符串化并用逗号分隔,可以有效地存储多个城市搜索记录,并在需要时检索出来。此外,还提供了一个检查和清理历史记录的机制,确保记录数量不超过设定上限。
2643

被折叠的 条评论
为什么被折叠?



