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

第一步:创建SQLite数据库RecordSQLiteOpenHelper.java

1package com.mobile.android.yilone.sqlite; 2 3import android.content.Context; 4import android.database.sqlite.SQLiteDatabase; 5import android.database.sqlite.SQLiteDatabase.CursorFactory; 6import android.database.sqlite.SQLiteOpenHelper; 7 8public class RecordSQLiteOpenHelper extends SQLiteOpenHelper { 9     10    private static final String name="temp.db"; 11    private static final Integer version=1; 12 13    public RecordSQLiteOpenHelper(Context context) { 14        super(context, name, null, version); 15        // TODO Auto-generated constructor stub 16    } 17 18    /** 19     * 创建表 20     * */ 21    @Override 22    public void onCreate(SQLiteDatabase db) { 23         24        db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))"); 25         26    } 27     28    /** 29    * 30    */ 31    @Override 32    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 33        // TODO Auto-generated method stub 34 35    } 36 37}

第二步,重写ListView,防止在嵌套SrcollView时滚动失效

1package com.mobile.android.yiloneshop.view; 2 3import android.content.Context; 4import android.util.AttributeSet; 5import android.widget.ListView; 6 7public class MyListView extends ListView { 8     9    public MyListView(Context context) { 10        super(context); 11      } 12      13      public MyListView(Context context, AttributeSet attrs) { 14        super(context, attrs); 15      } 16      17      public MyListView(Context context, AttributeSet attrs, int defStyle) { 18        super(context, attrs, defStyle); 19      } 20      21      @Override 22      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 23        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, 24            MeasureSpec.AT_MOST); 25        super.onMeasure(widthMeasureSpec, expandSpec); 26      } 27}

第三步:创建布局

1<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2  xmlns:tools="http://schemas.android.com/tools" 3  android:layout_width="match_parent" 4  android:layout_height="match_parent" 5  android:focusableInTouchMode="true" 6  android:orientation="vertical" 7  tools:context="${relativePackage}.${activityClass}"> 8  9  <LinearLayout 10    android:layout_width="fill_parent" 11    android:layout_height="50dp" 12    android:background="#E54141" 13    android:orientation="horizontal" 14    android:paddingRight="16dp"> 15  16    <ImageView 17      android:layout_width="45dp" 18      android:layout_height="45dp" 19      android:layout_gravity="center_vertical" 20      android:padding="10dp" 21      android:src="@drawable/back" /> 22  23    <EditText 24      android:id="@+id/et_search" 25      android:layout_width="0dp" 26      android:layout_height="match_parent" 27      android:layout_weight="1" 28      android:background="@null" 29      android:drawableLeft="@drawable/search" 30      android:drawablePadding="8dp" 31      android:gravity="start|center_vertical" 32      android:hint="输入查询的关键字" 33      android:imeOptions="actionSearch" 34      android:singleLine="true" 35      android:textColor="@android:color/white" 36      android:textSize="16sp" /> 37  38  </LinearLayout> 39  40  41  <ScrollView 42    android:layout_width="wrap_content" 43    android:layout_height="wrap_content"> 44  45    <LinearLayout 46      android:layout_width="match_parent" 47      android:layout_height="wrap_content" 48      android:orientation="vertical"> 49  50      <LinearLayout 51        android:layout_width="match_parent" 52        android:layout_height="wrap_content" 53        android:orientation="vertical" 54        android:paddingLeft="20dp" 55  56        > 57  58        <TextView 59          android:id="@+id/tv_tip" 60          android:layout_width="match_parent" 61          android:layout_height="50dp" 62          android:gravity="left|center_vertical" 63          android:text="搜索历史" /> 64  65        <View 66          android:layout_width="match_parent" 67          android:layout_height="1dp" 68          android:background="#EEEEEE"></View> 69  70        <com.cwvs.microlife.MyListView 71          android:id="@+id/listView" 72          android:layout_width="match_parent" 73          android:layout_height="wrap_content"></com.cwvs.microlife.MyListView> 74  75  76      </LinearLayout> 77  78      <View 79        android:layout_width="match_parent" 80        android:layout_height="1dp" 81        android:background="#EEEEEE"></View> 82  83      <TextView 84        android:id="@+id/tv_clear" 85        android:layout_width="match_parent" 86        android:layout_height="40dp" 87        android:background="#F6F6F6" 88        android:gravity="center" 89        android:text="清除搜索历史" /> 90  91      <View 92        android:layout_width="match_parent" 93        android:layout_height="1dp" 94        android:layout_marginBottom="20dp" 95        android:background="#EEEEEE"></View> 96    </LinearLayout> 97  98  </ScrollView> 99</LinearLayout>

第四步:Activity的实现

1package com.cwvs.microlife; 2  3import java.util.Date; 4  5import android.app.Activity; 6import android.content.Context; 7import android.database.Cursor; 8import android.database.sqlite.SQLiteDatabase; 9import android.graphics.drawable.Drawable; 10import android.os.Bundle; 11import android.text.Editable; 12import android.text.TextWatcher; 13import android.view.KeyEvent; 14import android.view.View; 15import android.view.Window; 16import android.view.inputmethod.InputMethodManager; 17import android.widget.AdapterView; 18import android.widget.BaseAdapter; 19import android.widget.CursorAdapter; 20import android.widget.EditText; 21import android.widget.SimpleCursorAdapter; 22import android.widget.TextView; 23import android.widget.Toast; 24  25public class MainActivity extends Activity { 26  27  private EditText et_search; 28  private TextView tv_tip; 29  private MyListView listView; 30  private TextView tv_clear; 31  private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);; 32  private SQLiteDatabase db; 33  private BaseAdapter adapter; 34  35  @Override 36  protected void onCreate(Bundle savedInstanceState) { 37    super.onCreate(savedInstanceState); 38    requestWindowFeature(Window.FEATURE_NO_TITLE); 39    setContentView(R.layout.activity_main); 40    // 初始化控件 41    initView(); 42  43    // 清空搜索历史 44    tv_clear.setOnClickListener(new View.OnClickListener() { 45      @Override 46      public void onClick(View v) { 47        deleteData(); 48        queryData(""); 49      } 50    }); 51  52    // 搜索框的键盘搜索键点击回调 53    et_search.setOnKeyListener(new View.OnKeyListener() {// 输入完后按键盘上的搜索键 54  55      public boolean onKey(View v, int keyCode, KeyEvent event) { 56        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能 57          // 先隐藏键盘 58          ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow( 59              getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 60          // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存 61          boolean hasData = hasData(et_search.getText().toString().trim()); 62          if (!hasData) { 63            insertData(et_search.getText().toString().trim()); 64            queryData(""); 65          } 66          // TODO 根据输入的内容模糊查询商品,并跳转到另一个界面,由你自己去实现 67          Toast.makeText(MainActivity.this, "clicked!", Toast.LENGTH_SHORT).show(); 68  69        } 70        return false; 71      } 72    }); 73  74    // 搜索框的文本变化实时监听 75    et_search.addTextChangedListener(new TextWatcher() { 76      @Override 77      public void beforeTextChanged(CharSequence s, int start, int count, int after) { 78  79      } 80  81      @Override 82      public void onTextChanged(CharSequence s, int start, int before, int count) { 83  84      } 85  86      @Override 87      public void afterTextChanged(Editable s) { 88        if (s.toString().trim().length() == 0) { 89          tv_tip.setText("搜索历史"); 90        } else { 91          tv_tip.setText("搜索结果"); 92        } 93        String tempName = et_search.getText().toString(); 94        // 根据tempName去模糊查询数据库中有没有数据 95        queryData(tempName); 96  97      } 98    }); 99  100    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 101      @Override 102      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 103        TextView textView = (TextView) view.findViewById(android.R.id.text1); 104        String name = textView.getText().toString(); 105        et_search.setText(name); 106        Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show(); 107        // TODO 获取到item上面的文字,根据该关键字跳转到另一个页面查询,由你自己去实现 108      } 109    }); 110  111    // 插入数据,便于测试,否则第一次进入没有数据怎么测试呀? 112    Date date = new Date(); 113    long time = date.getTime(); 114    insertData("Leo" + time); 115  116    // 第一次进入查询所有的历史记录 117    queryData(""); 118  } 119  120  /** 121   * 插入数据 122   */ 123  private void insertData(String tempName) { 124    db = helper.getWritableDatabase(); 125    db.execSQL("insert into records(name) values('" + tempName + "')"); 126    db.close(); 127  } 128  129  /** 130   * 模糊查询数据 131   */ 132  private void queryData(String tempName) { 133    Cursor cursor = helper.getReadableDatabase().rawQuery( 134        "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null); 135    // 创建adapter适配器对象 136    adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[] { "name" }, 137        new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); 138    // 设置适配器 139    listView.setAdapter(adapter); 140    adapter.notifyDataSetChanged(); 141  } 142  /** 143   * 检查数据库中是否已经有该条记录 144   */ 145  private boolean hasData(String tempName) { 146    Cursor cursor = helper.getReadableDatabase().rawQuery( 147        "select id as _id,name from records where name =?", new String[]{tempName}); 148    //判断是否有下一个 149    return cursor.moveToNext(); 150  } 151  152  /** 153   * 清空数据 154   */ 155  private void deleteData() { 156    db = helper.getWritableDatabase(); 157    db.execSQL("delete from records"); 158    db.close(); 159  } 160  161  private void initView() { 162    et_search = (EditText) findViewById(R.id.et_search); 163    tv_tip = (TextView) findViewById(R.id.tv_tip); 164    listView = (com.cwvs.microlife.MyListView) findViewById(R.id.listView); 165    tv_clear = (TextView) findViewById(R.id.tv_clear); 166  167    // 调整EditText左边的搜索按钮的大小 168    Drawable drawable = getResources().getDrawable(R.drawable.search); 169    drawable.setBounds(0, 0, 60, 60);// 第一0是距左边距离,第二0是距上边距离,60分别是长宽 170    et_search.setCompoundDrawables(drawable, null, null, null);// 只放左边 171  } 172}

注:转载自http://www.jb51.net/article/80654.htm

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

SpringBoot整合Redis乱码原因及解决方案

问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa