首页 > 编程语言 > android实现搜索功能并将搜索结果保存到SQLite中(实例代码)
2020
09-27

android实现搜索功能并将搜索结果保存到SQLite中(实例代码)

运行结果:


涉及要点:

  • ListView+EditText+ScrollView实现搜索效果显示
  • 监听软键盘回车执行搜索
  • 使用TextWatcher( )实时筛选
  • 将搜索内容存储到SQLite中(可清空历史记录)
  • 监听EditText的焦点,获得焦点弹出软键盘同时显示搜索历史,失去焦点隐藏软件盘和ListView。

实现过程比较简单,都是常用的,这里就不讲解了。代码可直接复制使用。

实现过程:

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
public class MainActivity extends Activity {
 
 private EditText et_search;
 private TextView tv_tip;
 private MyListView listView;
 private TextView tv_clear;
 ScrollView scrollView;
 private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
 private SQLiteDatabase db;
 private BaseAdapter adapter;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 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("");
   }
   Toast.makeText(MainActivity.this, "点击软键盘搜索!", Toast.LENGTH_SHORT).show();
  }
  return false;
  }
 });
 
 et_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
  @Override
  public void onFocusChange(View view, boolean b) {
  if (b) { //获得
   scrollView.setVisibility(View.VISIBLE);
  } else {//市区焦点
   scrollView.setVisibility(View.GONE);
  }
  }
 });
 
 // 搜索框的文本变化实时监听
 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();
  ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
   getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); //隐藏软键盘
  et_search.clearFocus();
  et_search.setText("");
  }
 });
 
 // 插入测试数据
 Date date = new Date();
 long time = date.getTime();
 insertData("LY" + 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);
 scrollView = findViewById(R.id.showSearch);
 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);// 只放左边
 }
}

RecordSQLiteOpenHelper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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) {
 
 }
}

MyListView.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:focusable="true"
 android:focusableInTouchMode="true"
 android:orientation="vertical"
 tools:context=".MainActivity">
 
 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="50dp"
 android:background="#be9999"
 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="fill_parent"
  android:layout_weight="264"
  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:id="@+id/showSearch"
 android:layout_width="wrap_content"
 android:layout_height="300dp"
 android:visibility="gone">
 
 <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" />
 
  <liyue.edu.cn.ncst.app.MyListView
   android:id="@+id/listView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" />
  </LinearLayout>
 
  <View
  android:layout_width="match_parent"
  android:layout_height="1dp"
  android:background="#EEEEEE" />
 
  <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" />
 </LinearLayout>
 
 </ScrollView>
 
</LinearLayout>

完整代码下载 demo

到此这篇关于android实现搜索功能并将搜索结果保存到SQLite中(实例代码)的文章就介绍到这了,更多相关android 搜索功能搜索结果保存sqlite内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

编程技巧