The Android search function saves the search history locally.

Source: Internet
Author: User

The Android search function saves the search history locally.

The APP developed by my colleague has a search function and needs to display the search history. In my spare time, I helped her develop this function. Now I will extract this page into a demo and share it with you.

Effect:

This case is easy to implement, so it can be used directly in the project, involving knowledge points:
-Database addition, deletion, modification, and query operations
-Resolve nested conflicts between ListView and ScrollView
-Listen to the keyboard, press enter, and set it to search.
-Use TextWatcher () for Real-Time Filtering
-Search keywords again and add them to the database
-When you enter the page, the soft keyboard is automatically displayed instead of EditText.

Code

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 lis TView; private TextView TV _clear; private response 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); // initialize the control initView (); // clear the search history TV _clear.setOnClic KListener (new View. onClickListener () {@ Override public void onClick (View v) {deleteData (); queryData ("");}}); // click the keyboard search key in the search box and call back et_search.setOnKeyListener (new View. onKeyListener () {// press the search key public boolean onKey (View v, int keyCode, KeyEvent event) {if (keyCode = KeyEvent. KEYCODE_ENTER & event. getAction () = KeyEvent. ACTION_DOWN) {// modify the Enter key function // hide the keyboard (InputMethodManager) getSystemServ Ice (Context. INPUT_METHOD_SERVICE )). hideSoftInputFromWindow (getCurrentFocus (). getWindowToken (), InputMethodManager. HIDE_NOT_ALWAYS); // press the search key to save the keyword of the current query. If the keyword already exists, the boolean hasData = hasData (et_search.getText () will not be saved (). toString (). trim (); if (! HasData) {insertData (et_search.getText (). toString (). trim (); queryData ("") ;}// TODO fuzzy queries the product based on the input content and jumps to another interface. You can implement Toast on your own. makeText (MainActivity. this, "clicked! ", Toast. LENGTH_SHORT ). show () ;}return false ;}}); // real-time listening for text changes in the search box 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 ("search history");} else {TV _tip.setText ("search result");} String tempName = et_search.getText (). toString (); // fuzzy query the database for queryData (tempName) based on 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 obtains the text above the item and jumps to another page for query based on this keyword. You can implement it yourself}); // inserts data for testing, otherwise, how can I test if no data is found for the first time? Date date = new Date (); long time = date. getTime (); insertData ("Leo" + time); // query all historical records for the first time ("");} /*** insert data */private void insertData (String tempName) {db = helper. getWritableDatabase (); db.exe cSQL ("insert into records (name) values ('" + tempName + "')"); db. close ();}/*** fuzzy query data */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 ); // create the adapter Object 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); // sets the adapter listView. setAdapter (adapter); adapter. notifyDataSetChanged ();}/*** check whether the database already has this Records */private boolean hasData (String tempName) {Cursor cursor = helper. getReadableDatabase (). rawQuery ("select id as _ id, name from records where name =? ", New String [] {tempName}); // determines whether a return cursor exists. moveToNext ();}/*** clear data */private void deleteData () {db = helper. getWritableDatabase (); db.exe cSQL ("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); // adjust the size of the Search button on the left of EditText. Drawable drawable = getResources (). getDrawable (R. drawable. search); drawable. setBounds (0, 0, 60, 60); // The first 0 is the left distance, the second 0 is the top distance, and the 60 is the long and wide et_search.setCompoundDrawables (drawable, null, null, null); // left only }}
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
<Code class = "hljs 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 = "fill_parent" android: layout_weight = "264" android: background = "@ null" android: drawableleft = "@ drawable/search" android: drawablepadding = "8dp" android: gravity = "start | center_vertical" android: hint = "Enter the query keyword" android: imeoptions = "actionSearch" android: singleline = "true" android: textcolor = "@ android: color/white "android: textsize =" 16sp "> </edittext> </imageview> </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 = "search history"> <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> </textview> </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 = "Clear search history"> <view android: layout_width = "match_parent" android: layout_height = "1dp" android: layout_marginbottom = "20dp" android: background = "# EEEEEE"> </view> </textview> </linearlayout> </scrollview> </linearlayout> </code>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.