Android实现搜索功能并本地保存搜索历史记录

时间:2021-07-04 16:38:24

本文实例为大家分享了android实现搜索功能,并且需要显示搜索的历史记录,供大家参考,具体内容如下

效果图:

Android实现搜索功能并本地保存搜索历史记录

本案例实现起来很简单,所以可以直接拿来嵌入项目中使用,涉及到的知识点:
- 数据库的增删改查操作
- listview和scrollview的嵌套冲突解决
- 监听软键盘回车按钮设置为搜索按钮
- 使用textwatcher( )实时筛选
- 已搜索的关键字再次搜索不重复添加到数据库
- 刚进入页面设置软键盘不因为edittext而自动弹出

代码

recordsqliteopenhelper.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.cwvs.microlife;
 
import android.content.context;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqliteopenhelper;
 
public class recordsqliteopenhelper extends sqliteopenhelper {
 
  private static string name = "temp.db";
  private static integer version = 1;
 
  public recordsqliteopenhelper(context context) {
    super(context, name, null, version);
  }
 
  @override
  public void oncreate(sqlitedatabase db) {
    db.execsql("create table records(id integer primary key autoincrement,name varchar(200))");
  }
 
  @override
  public void onupgrade(sqlitedatabase db, int oldversion, int newversion) {
 
  }
 
 
}

mainactivity.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package com.cwvs.microlife;
 
import java.util.date;
 
import android.app.activity;
import android.content.context;
import android.database.cursor;
import android.database.sqlite.sqlitedatabase;
import android.graphics.drawable.drawable;
import android.os.bundle;
import android.text.editable;
import android.text.textwatcher;
import android.view.keyevent;
import android.view.view;
import android.view.window;
import android.view.inputmethod.inputmethodmanager;
import android.widget.adapterview;
import android.widget.baseadapter;
import android.widget.cursoradapter;
import android.widget.edittext;
import android.widget.simplecursoradapter;
import android.widget.textview;
import android.widget.toast;
 
public class mainactivity extends activity {
 
  private edittext et_search;
  private textview tv_tip;
  private mylistview listview;
  private textview tv_clear;
  private recordsqliteopenhelper helper = new recordsqliteopenhelper(this);;
  private sqlitedatabase db;
  private baseadapter adapter;
 
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    requestwindowfeature(window.feature_no_title);
    setcontentview(r.layout.activity_main);
    // 初始化控件
    initview();
 
    // 清空搜索历史
    tv_clear.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        deletedata();
        querydata("");
      }
    });
 
    // 搜索框的键盘搜索键点击回调
    et_search.setonkeylistener(new view.onkeylistener() {// 输入完后按键盘上的搜索键
 
      public boolean onkey(view v, int keycode, keyevent event) {
        if (keycode == keyevent.keycode_enter && event.getaction() == keyevent.action_down) {// 修改回车键功能
          // 先隐藏键盘
          ((inputmethodmanager) getsystemservice(context.input_method_service)).hidesoftinputfromwindow(
              getcurrentfocus().getwindowtoken(), inputmethodmanager.hide_not_always);
          // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
          boolean hasdata = hasdata(et_search.gettext().tostring().trim());
          if (!hasdata) {
            insertdata(et_search.gettext().tostring().trim());
            querydata("");
          }
          // todo 根据输入的内容模糊查询商品,并跳转到另一个界面,由你自己去实现
          toast.maketext(mainactivity.this, "clicked!", toast.length_short).show();
 
        }
        return false;
      }
    });
 
    // 搜索框的文本变化实时监听
    et_search.addtextchangedlistener(new textwatcher() {
      @override
      public void beforetextchanged(charsequence s, int start, int count, int after) {
 
      }
 
      @override
      public void ontextchanged(charsequence s, int start, int before, int count) {
 
      }
 
      @override
      public void aftertextchanged(editable s) {
        if (s.tostring().trim().length() == 0) {
          tv_tip.settext("搜索历史");
        } else {
          tv_tip.settext("搜索结果");
        }
        string tempname = et_search.gettext().tostring();
        // 根据tempname去模糊查询数据库中有没有数据
        querydata(tempname);
 
      }
    });
 
    listview.setonitemclicklistener(new adapterview.onitemclicklistener() {
      @override
      public void onitemclick(adapterview<?> parent, view view, int position, long id) {
        textview textview = (textview) view.findviewbyid(android.r.id.text1);
        string name = textview.gettext().tostring();
        et_search.settext(name);
        toast.maketext(mainactivity.this, name, toast.length_short).show();
        // todo 获取到item上面的文字,根据该关键字跳转到另一个页面查询,由你自己去实现
      }
    });
 
    // 插入数据,便于测试,否则第一次进入没有数据怎么测试呀?
    date date = new date();
    long time = date.gettime();
    insertdata("leo" + time);
 
    // 第一次进入查询所有的历史记录
    querydata("");
  }
 
  /**
   * 插入数据
   */
  private void insertdata(string tempname) {
    db = helper.getwritabledatabase();
    db.execsql("insert into records(name) values('" + tempname + "')");
    db.close();
  }
 
  /**
   * 模糊查询数据
   */
  private void querydata(string tempname) {
    cursor cursor = helper.getreadabledatabase().rawquery(
        "select id as _id,name from records where name like '%" + tempname + "%' order by id desc ", null);
    // 创建adapter适配器对象
    adapter = new simplecursoradapter(this, android.r.layout.simple_list_item_1, cursor, new string[] { "name" },
        new int[] { android.r.id.text1 }, cursoradapter.flag_register_content_observer);
    // 设置适配器
    listview.setadapter(adapter);
    adapter.notifydatasetchanged();
  }
  /**
   * 检查数据库中是否已经有该条记录
   */
  private boolean hasdata(string tempname) {
    cursor cursor = helper.getreadabledatabase().rawquery(
        "select id as _id,name from records where name =?", new string[]{tempname});
    //判断是否有下一个
    return cursor.movetonext();
  }
 
  /**
   * 清空数据
   */
  private void deletedata() {
    db = helper.getwritabledatabase();
    db.execsql("delete from records");
    db.close();
  }
 
  private void initview() {
    et_search = (edittext) findviewbyid(r.id.et_search);
    tv_tip = (textview) findviewbyid(r.id.tv_tip);
    listview = (com.cwvs.microlife.mylistview) findviewbyid(r.id.listview);
    tv_clear = (textview) findviewbyid(r.id.tv_clear);
 
    // 调整edittext左边的搜索按钮的大小
    drawable drawable = getresources().getdrawable(r.drawable.search);
    drawable.setbounds(0, 0, 60, 60);// 第一0是距左边距离,第二0是距上边距离,60分别是长宽
    et_search.setcompounddrawables(drawable, null, null, null);// 只放左边
  }
}

mylistview.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.cwvs.microlife;
 
import android.content.context;
import android.util.attributeset;
import android.widget.listview;
 
public class mylistview extends listview {
  public mylistview(context context) {
    super(context);
  }
 
  public mylistview(context context, attributeset attrs) {
    super(context, attrs);
  }
 
  public mylistview(context context, attributeset attrs, int defstyle) {
    super(context, attrs, defstyle);
  }
 
  @override
  protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
    int expandspec = measurespec.makemeasurespec(integer.max_value >> 2,
        measurespec.at_most);
    super.onmeasure(widthmeasurespec, expandspec);
  }
 
}

activity_main.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:focusableintouchmode="true"
  android:orientation="vertical"
  tools:context="${relativepackage}.${activityclass}">
 
  <linearlayout
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:background="#e54141"
    android:orientation="horizontal"
    android:paddingright="16dp">
 
    <imageview
      android:layout_width="45dp"
      android:layout_height="45dp"
      android:layout_gravity="center_vertical"
      android:padding="10dp"
      android:src="@drawable/back" />
 
    <edittext
      android:id="@+id/et_search"
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:background="@null"
      android:drawableleft="@drawable/search"
      android:drawablepadding="8dp"
      android:gravity="start|center_vertical"
      android:hint="输入查询的关键字"
      android:imeoptions="actionsearch"
      android:singleline="true"
      android:textcolor="@android:color/white"
      android:textsize="16sp" />
 
  </linearlayout>
 
 
  <scrollview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
 
    <linearlayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
 
      <linearlayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingleft="20dp"
 
        >
 
        <textview
          android:id="@+id/tv_tip"
          android:layout_width="match_parent"
          android:layout_height="50dp"
          android:gravity="left|center_vertical"
          android:text="搜索历史" />
 
        <view
          android:layout_width="match_parent"
          android:layout_height="1dp"
          android:background="#eeeeee"></view>
 
        <com.cwvs.microlife.mylistview
          android:id="@+id/listview"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"></com.cwvs.microlife.mylistview>
 
 
      </linearlayout>
 
      <view
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#eeeeee"></view>
 
      <textview
        android:id="@+id/tv_clear"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#f6f6f6"
        android:gravity="center"
        android:text="清除搜索历史" />
 
      <view
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginbottom="20dp"
        android:background="#eeeeee"></view>
    </linearlayout>
 
  </scrollview>
</linearlayout>

以上就是本文的全部内容,希望对大家的学习有所帮助。