Android实现搜索历史记录的本地存储。

主要通过SharedPreferences进行存储,难点主要是1.倒序显示 2.去重 3.最多显示n条。话不多说看代码

private final static String PREFERENCE_NAME = "superservice_ly";
private final static String SEARCH_HISTORY="linya_history";
// 保存搜索记录
    public static void saveSearchHistory(String inputText) {
        SharedPreferences sp = App.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        if (TextUtils.isEmpty(inputText)) {
            return;
        }
        String longHistory = sp.getString(SEARCH_HISTORY, "");  //获取之前保存的历史记录
        String[] tmpHistory = longHistory.split(","); //逗号截取 保存在数组中
        List<String> historyList = new ArrayList<String>(Arrays.asList(tmpHistory)); //将改数组转换成ArrayList
        SharedPreferences.Editor editor = sp.edit();
        if (historyList.size() > 0) {
            //1.移除之前重复添加的元素
            for (int i = 0; i < historyList.size(); i++) {
                if (inputText.equals(historyList.get(i))) {
                    historyList.remove(i);
                    break;
                }
            }
            historyList.add(0, inputText); //将新输入的文字添加集合的第0位也就是最前面(2.倒序)
            if (historyList.size() > 8) {
                historyList.remove(historyList.size() - 1); //3.最多保存8条搜索记录 删除最早搜索的那一项
            }
            //逗号拼接
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < historyList.size(); i++) {
                sb.append(historyList.get(i) + ",");
            }
            //保存到sp
            editor.putString(SEARCH_HISTORY, sb.toString());
            editor.commit();
        } else {
            //之前未添加过
            editor.putString(SEARCH_HISTORY, inputText + ",");
            editor.commit();
        }
    }
//获取搜索记录
    public static List<String> getSearchHistory(){
        SharedPreferences sp = App.context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        String longHistory =sp.getString(SEARCH_HISTORY, "");
        String[] tmpHistory = longHistory.split(","); //split后长度为1有一个空串对象
        List<String> historyList = new ArrayList<String>(Arrays.asList(tmpHistory));
        if (historyList.size() == 1 && historyList.get(0).equals("")) { //如果没有搜索记录,split之后第0位是个空串的情况下
            historyList.clear();  //清空集合,这个很关键
        }
        return historyList;
    }

代码就这些,放到你的工具类里面,在你需要的地方调用就好了。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 179,236评论 25 708
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,059评论 2 59
  • 第一章 岁月静好 笔尖涩涩的,写不出字来,只在白纸上留下带着干涸墨迹、令人难堪的凹迹。沈清终究还是抓起了钢笔,在演...
    许日清阅读 469评论 3 2
  • 我曾有一刻钟的迟疑 是要继续思维的不切实际 还是拖过被子 沉沉睡去 我憎恶这喑哑的夜 风中骚动的窗帘 狰狞的剪影...
    煤灰大仙阅读 189评论 0 0
  • 前言: 还记得你当初为什么加入007吗?不忘初心,不忘初心,不忘初心~~ 1.概括: 和时间做朋友是我们理想状态,...
    winwinwings阅读 366评论 0 4

友情链接更多精彩内容