//保存搜索历史,保存到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 发布