Android implements the search feature and saves the search history locally _android

Source: Internet
Author: User
Tags gettext sqlite

This example for you to share the Android search function, and need to display the history of the search for your reference, the specific content as follows

Effect Chart:

This case is simple to implement, so it can be directly embedded in the project using the knowledge points involved:
-database additions and deletions to check operations
-Nested conflict resolution for ListView and ScrollView
-Monitor Soft keyboard return button set to search button
-Real-time filtering using Textwatcher ()
-Search for keywords again search not duplicate add to database
-Just enter the page to set the soft keyboard does not automatically eject because 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 {
    Super (context, name, null, version);
  }

  @Override public
  void OnCreate (Sqlitedatabase db) {
    db.execsql ("CREATE TABLE records" (ID integer primary key Autoincrement,name varchar) ");
  }

  @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);

    Initialize control Initview (); 
        Empty Search History Tv_clear.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (View v) {
        DeleteData ();
      Querydata ("");

    }
    });  Search box of the keyboard search key click Callback Et_search.setonkeylistener (New View.onkeylistener () {//Enter the keyboard after the search key public boolean onkey (View V, int keycode, keyevent event) {if (keycode = = Keyevent.keycode_enter && event.getaction () = KeyEvent. Action_down) {//Modify the Return key function//First hide the keyboard ((Inputmethodmanager) Getsystemservice (Context.input_method_service)
          ). Hidesoftinputfromwindow (Getcurrentfocus (). Getwindowtoken (), inputmethodmanager.hide_not_always); Saves the keyword for the current query after you press the search key, and does not perform the save if the keyword already exists boolean hasData = HasData (et_search.gettext (). toString (). Trim ());
            if (!hasdata) {InsertData (Et_search.gettext (). toString (). Trim ());
          Querydata (""); //TODO Query the product based on the input content, and jump to another interface, by yourself to achieve toast.maketext (Mainactivity.this, "clicked!", toast.length_s

        Hort). Show ();
      return false;

    }
    }); Text changes in the search box real-time listening Et_search.addtextchangedlistener (new Textwatcher () {@Override public void Beforetextchang Ed (charsequence s, int start, int count, int after) {} @Override public void ontextchanged (Charsequen
        Ce 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 results");
        String tempname = Et_search.gettext (). toString ();

      According to Tempname, there is no data querydata (tempname) in the fuzzy query database;

}
    });    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 gets the text above the item, jumps to another page query according to the keyword, and implements it by yourself}};
    Insert data, easy to test, otherwise first enter no data how to test it?
    Date date = new Date ();
    Long time = Date.gettime ();

    InsertData ("Leo" + time);
  First access to all historical records Querydata ("");
    /** * Insert data/private void InsertData (String tempname) {db = Helper.getwritabledatabase ();
    Db.execsql ("INSERT Into records (name) values (' + tempname + ')");
  Db.close (); /** * Fuzzy query data */private void Querydata (String tempname) {Cursor Cursor = Helper.getreadabledatabase (). RA
    Wquery (    "SELECT ID as _id,name from records where name is"% "+ tempname +"% ' ORDER by id DESC ", null); Create Adapter 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);
    Set adapter Listview.setadapter (adapter);
  Adapter.notifydatasetchanged (); /** * Check the database for this record */private Boolean hasData (String tempname) {Cursor Cursor = Helper.getreadabledata
    Base (). Rawquery ("SELECT ID as _id,name from records where name =?", new String[]{tempname});
  Determine if there is a next return Cursor.movetonext ();
    /** * EMPTY data * * 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);
    Adjusts the size of the search button on the left of the edittext drawable drawable = Getresources (). getdrawable (R.drawable.search); Drawable.setbounds (0, 0, 60, 60);//10th is the distance from the left, 20th is the distance from the top, 60 is the long width et_search.setcompounddrawables (drawable, NULL, NULL, n



 ULL);//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) {
    super (context);
  }

  Public Mylistview (context, AttributeSet attrs) {
    Super (context, attrs);
  }

  Public Mylistview (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_w 
      Idth= "45DP" android:layout_height= "45DP" android:layout_gravity= "center_vertical" android:padding= "10DP" android:src= "@drawable/back"/> <edittext android:id= "@+id/et_search" 0DP "android:layout_height=" Match_parent "android:layout_weight=" 1 "android:background=" @null "and roid:drawableleft= "@drawable/search" Android:drawablepadding= "8DP" android:gravity= "start|center_vertical" android:hint= "Enter the keyword" android:imeoptions= "of the query Actionsear

  Ch "android:singleline=" true "android:textcolor=" @android: Color/white "android:textsize=" 16sp "/> </LinearLayout> <scrollview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" &

    Gt <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:orient ation= "vertical" > <linearlayout android:layout_width= "match_parent" android:layout_height= "WR"
          Ap_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:lay Out_width= "MATCH_parent "android:layout_height=" 1DP "android:background=" #EEEEEE "></View> <com.c Wvs.microlife.MyListView android:id= "@+id/listview" android:layout_width= "Match_parent" Andr
        oid:layout_height= "Wrap_content" ></com.cwvs.microlife.MyListView> </LinearLayout> <view Android:layout_width= "Match_parent" android:layout_height= "1DP" android:background= "#EEEEEE" >&lt ;/view> <textview android:id= "@+id/tv_clear" android:layout_width= "Match_parent" Andr oid:layout_height= "40DP" android:background= "#F6F6F6" android:gravity= "center" android:text= "clears the search calendar History "/> <view android:layout_width=" match_parent "android:layout_height=" 1DP "android:l Ayout_marginbottom= "20DP" android:background= "#EEEEEE" ></View> </LinearLayout> </scrollvi Ew> </linearlayout>
 

The above is the entire content of this article, I hope to help you learn.

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.