Android实现搜索功能并本地保存搜索历史记录
最后更新 2021-02-20 16:41 星期六 所属:
安卓教程 浏览:872
本实例完成起來非常简单,因此 能够立即用来置入新项目中应用,牵涉到的知识要点:
– 数据库查询的增删实际操作
– ListView和ScrollView的嵌入矛盾处理
– 监视软键盘回车键按键设定为检索按键
– 应用TextWatcher( )即时挑选
– 已检索的关键词再度检索不反复加上到数据库查询
– 刚进到页面布局软键盘不由于EditText而自弹出出
编码
RecordSQLiteOpenHelper.java
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
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
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
<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>
之上便是文中的所有内容,期待对大伙儿的学习培训有一定的协助。
