欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-09 19:26:04
运行结果:涉及要点: listview+edittext+scrollview实现搜索效果显示 监听软键盘回车执行搜索 使用textwatcher( )实时筛选 将搜索内容存储到sqlite中...

运行结果:

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

涉及要点:

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

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

实现过程:

mainactivity.java

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

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

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: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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!