网上有许多这方面的教程,思来想去还是决定写下我自己的代码,为了方便以后复习查看。
先看效果图:

实现如下功能
1、数据库的增删改查操作
2、已搜索的关键字再次搜索不会重复添加到数据库
3、点击的记录可添加到搜索框里

XML布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:padding="10dp"android:orientation="vertical"tools:context=".SearchActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><EditTextandroid:id="@+id/search_et_search"android:layout_width="match_parent"android:layout_height="35dp"android:layout_marginRight="2dp"android:background="@drawable/et_style_search"android:hint="    搜索 "android:drawableLeft="@drawable/search"android:paddingLeft="5dp"android:singleLine="true"android:layout_weight="1"/><ImageViewandroid:id="@+id/voice_iv"android:layout_width="25dp"android:layout_height="30dp"android:src="@drawable/voice"android:layout_gravity="center"android:layout_marginRight="5dp"/><TextViewandroid:id="@+id/cancel_tv_search"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:text="取消"android:textSize="20sp"android:textColor="#257bf4"/></LinearLayout><ListViewandroid:id="@+id/search_record_iv"android:layout_width="match_parent"android:layout_height="wrap_content"></ListView><Viewandroid:layout_width="match_parent"android:layout_height="0.05dp"android:background="#4a949393"/><TextViewandroid:id="@+id/clearReocrds_tv"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:textAlignment="center"android:visibility="gone"android:text="清除历史记录"android:textSize="12sp" /></LinearLayout>

创建listview_item.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"android:layout_height="match_parent"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"><ImageViewandroid:id="@+id/search_record_image_iv"android:layout_width="20dp"android:layout_height="20dp"android:src="@drawable/record"android:layout_gravity="center_vertical"android:layout_marginLeft="15dp"/><TextViewandroid:id="@+id/search_content_tv"android:layout_width="match_parent"android:layout_height="20dp"android:layout_margin="10dp"android:layout_gravity="center_vertical"/></LinearLayout></LinearLayout>

Java代码

1、

public class RecordsSQLiteOpenHelper extends SQLiteOpenHelper {//声明一个代表数据库名称的字符串private final static  String DB_NAME = "MyRecords.db";//声明一个代表数据库版本的整形变量private static int DB_VERSION = 1;public RecordsSQLiteOpenHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {//建立records表格String sql = "CREATE TABLE IF NOT EXISTS records (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";db.execSQL(sql);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}

2、继承ArrayAdapter类,编写RecordsAdapter适配器类

public class RecordsAdapter extends ArrayAdapter {//定义一个整型,记录‘显示记录的文本’的idprivate int resourceId;public RecordsAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {super(context, resource, objects);resourceId = resource;}@NonNull@Overridepublic View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {View view = LayoutInflater.from(getContext()).inflate(resourceId,null);   //实例化一个对象TextView showRecord = (TextView)view.findViewById(R.id.search_content_tv);String record = (String)getItem(position);     //获取当前的记录字符串showRecord.setText(record);return view;}
}

3、编写搜索记录操作类

/*** 搜索记录操作类* 用于封装度对搜索记录的各种操作*/
public class RecordsDao {RecordsSQLiteOpenHelper recordHelper;  //定义一个数据库的操作帮助对象SQLiteDatabase recordDb;               //定义一个记录的数据库对象public RecordsDao(Context context){recordHelper = new RecordsSQLiteOpenHelper(context);}/*** 该函数用于添加搜索记录*/public void addRecords(String record){if (!isHasRecord(record)){     //判断源数据中是否已有该记录recordDb = recordHelper.getWritableDatabase();   //获取搜索记录数据库ContentValues value = new ContentValues();value.put("name",record);recordDb.insert("records",null,value);    //插入记录recordDb.close();}}/*** 该函数用于获取全部搜索记录* @return List<String>*/public List<String> getRecordsList(){List<String> recordsList = new ArrayList<String>();recordDb = recordHelper.getReadableDatabase();Cursor cursor = recordDb.query("records",null,null,null,null,null,null);while (cursor.moveToNext()){String record = cursor.getString(cursor.getColumnIndexOrThrow("name"));recordsList.add(record);}recordDb.close();cursor.close();return recordsList;}/*** 该函数用于清空搜索记录*/public void clearRecords(){String sql = "delete from records";recordDb = recordHelper.getWritableDatabase();recordDb.execSQL(sql);recordDb.close();}/*** 该函数用于模糊查询*/public List<String> querySimilarRecords(String record){String sql = "select * from records where name like'%" + record + "%' order by name";// String queryStr = "select * from records where name like '%" + record + "%' order by name ";List<String> similarRecordsList = new ArrayList<String>();recordDb = recordHelper.getReadableDatabase();Cursor cursor = recordDb.rawQuery(sql,null);while (cursor.moveToNext()){String myRecord = cursor.getString(cursor.getColumnIndexOrThrow("name"));similarRecordsList.add(myRecord);}recordDb.close();cursor.close();return similarRecordsList;}/*** 该函数用于判断原数据库中是否已有该记录* @return 有记录返回true*/private boolean isHasRecord(String record){boolean isHasRecord = false;recordDb = recordHelper.getReadableDatabase();Cursor cursor = recordDb.query("records",null,null,null,null,null,null);while (cursor.moveToNext()){if (record.equals(cursor.getString(cursor.getColumnIndexOrThrow("name")))){isHasRecord = true;break;}}recordDb.close();cursor.close();return isHasRecord;}
}

4、接下来是在MainActivity里的代码了,我是在我练习的一个项目里实现了这部分功能,代码多而杂。下面是关键性代码

 recordsDao = new RecordsDao(SearchActivity.this);
/*** 绑定适配器*/void bindAdapter(){recordsList = recordsDao.getRecordsList();    //获取搜索记录的数组reversedRecords();ckeckRecords();                                //检查是否有记录recordsAdapter = new RecordsAdapter(SearchActivity.this,R.layout.listview_item,recordsList);records_lv.setAdapter(recordsAdapter);}
 /*** 该函数用于反转搜索记录*/private void reversedRecords(){String temp = "";int size = (recordsList.size())/2;int foot = recordsList.size()-1;//下面的循环实现数组首尾置换for (int i=0;i<size;i++){foot = foot - i;temp = recordsList.get(i);recordsList.set(i,recordsList.get(foot));recordsList.set(foot,temp);}}
 /*** 创建一个“历史记录”列表的监听器对象* 点击记录,可把该记录添加到搜索框里*/AdapterView.OnItemClickListener lvListener = new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {String myClicked = recordsList.get(position);search_et.setText(myClicked);}};
 /*** 创建一个“清除历史记录”的监听器对象*/View.OnClickListener clearListener = new View.OnClickListener() {@Overridepublic void onClick(View v) {recordsList.clear();recordsDao.clearRecords();recordsAdapter.notifyDataSetChanged();ckeckRecords();}};

上面的代码有许多细节没有放出来。还有一些功能没有实现,比如:监听软键盘回车按钮设置为搜索按钮、 使用TextWatcher( )进行实时筛选 等

更详细的代码参考这两位大神的文章
Android—— ListView 的简单用法及定制ListView界面
简单实现Android搜索功能 显示清除历史搜索记录

Android 显示历史搜索记录相关推荐

  1. Android常用:手把手教你实现搜索框(含历史搜索记录)

    http://blog.csdn.net/carson_ho/article/details/53366570 前言 像下图的搜索功能在Android开发中非常常见 今天我将手把手教大家如何实现具备历 ...

  2. Android开源实战:SearchView搜索框(含历史搜索记录)

    前言 Android开发中,类似下图的搜索功能非常常见 搜索功能 今天,我将手把手教大家实现一款 封装了 历史搜索记录功能 & 样式 的Android 自定义搜索框 开源库,希望你们会喜欢. ...

  3. 实现历史搜索记录和搜索功能

    uniapp实现搜索功能和搜索历史记录 <template><view class="content"><!-- 搜索引擎 这里是模糊查询,后续会加上 ...

  4. Android简单实现搜索功能 显示清除历史搜索记录

    本文主要为大家分享了Android实现搜索功能,并且可以实时显示搜索的历史记录,根据输入的内容去模糊查询,供大家参考,界面图如下. 本案例实现起来也非常的简单,所以可以直接拿来嵌入项目中使用,主要涉及 ...

  5. Android 天气APP(十五)增加城市搜索、历史搜索记录

    上一篇:Android 天气APP(十四)修复UI显示异常.优化业务代码逻辑.增加详情天气显示 添加城市 新版------------------- 一.推荐城市数据 二.推荐城市item布局和适配器 ...

  6. Android开源实战:简单好用、含历史搜索记录的智能搜索框

    前言 Android开发中,类似下图的搜索功能非常常见 今天,我将带来一款 封装了 历史搜索记录功能 & 样式 的Android 自定义搜索框 开源库,希望你们会喜欢. 已在Github开源: ...

  7. Android原生控件SearchView实现历史搜索记录

    SearchView实现搜索记录看了一些大神写的贴子简单实现, 但我们功能 需要单独删除一条历史搜索记录,好像没在网上找到解决方案,原生方法上也只有suggestions.clearHistory() ...

  8. 微信小程序实现历史搜索记录的本地储存和删除

    输入框和搜索按钮表单的wxml,没啥特别的,这里绑定了输入框的输入值,样式我就不放上来了 <form class='searchForm' bindsubmit='searchSubmitFn' ...

  9. uni-app使用setStorageSync存储历史搜索记录,与setStorage区别

    一.setStorageSync与setStorage的区别 都可以将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容. setStorageSync:同步接口,需要 ...

  10. 【玩转SQLite系列】(六)SQLite数据库应用案例实现历史搜索记录

    转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53366564 本文出自[DylanAndroid的博客] [玩转SQLite系 ...

最新文章

  1. Udacity机器人软件工程师课程笔记(二十五) - 使用PID控制四轴飞行器 - 四轴飞行器(四旋翼)模拟器
  2. linux驱动:音频驱动(六)ASoc之codec设备
  3. python读取excel某一行内容-python3读取excel文件只提取某些行某些列的值方法
  4. iptables规则备份和恢复、firewall的zone的操作、service的操作
  5. 编译arm版本驱动模块
  6. 为人示弱,做事留余 | 摸鱼系列
  7. adodb.stream对象的方法/属性
  8. 【 js 基础 】Javascript “继承”
  9. [转]OPENGL中GLU和GLUT工具箱
  10. linux命令行使用
  11. ARKit入门到精通-1.5 -基础内容-史小川-专题视频课程
  12. java开发做项目的思路
  13. 一文搞懂深度学习所有工具——Anaconda、CUDA、cuDNN
  14. Conda 的 yml 文件 Conda/PIP 国内镜像源的添加
  15. Unity中的资源管理-资源类型和基本使用
  16. MySQL修改数据表中的字段名_MySQL修改数据表中的字段名
  17. 推荐10个程序员常去的网站
  18. 如何用Python操作Excel自动化办公?一个案例教会你openpyxl——图表设计和透视表
  19. 玩客云设置linux权限,玩客云退出链克怎么禁止硬盘缓存?.onething_data文件禁止缓存玩客云关闭上传退出链克...
  20. 2、二叉树的后序遍历

热门文章

  1. 【爬虫知识】浏览器开发者工具使用技巧总结
  2. (P46)面向对象版表达式计算器:让表达式计算器支持变量赋值 ,Calc类实现
  3. 磕技术、筑平台,浪潮存储如何持续破局?
  4. 数学概念: 导数和切线方程
  5. 30行代码实现蚂蚁森林自动偷能量
  6. 2023计算机毕业设计SSM最新选题之javaJava班级信息管理系统x0w9c
  7. 委托代理问题------The principal-agent problem
  8. html为知笔记模板,为知笔记如何建立模板教程
  9. 计算机桌面有边框阴影,“桌面图标下面有阴影的解决方案”的解决方案
  10. 【iMessage苹果群发】OpenSSL将重修立连接