EditText+listview+database operation to realize search function

What are the ways to implement the search function?

android search box function is very common, there are many ways to achieve the search box, there are three common:
- SearchView
- autocompletetextview
- EditText
- Customization

EditText+listview+database

This article mainly describes the following ways, not recommended to use sp storage. SP storage is not easy to control, and there is no database way to achieve simple, convenient for future management (may need to increase the demand for it)

  • Look at the picture first.

Identify the requirements for the required search functionality

This article provides the following requirements:

  • Enter keywords, click on the search, save the keywords, jump the corresponding search results interface
  • Enter the interface with search function again, input keywords to query the data pants automatically, and display the data (only input keywords will show the search history, default is not shown)
  • Empty historical data

1. Prepare a database help class SearchRecordSQHelper to create a table that holds search history

/**
 * Created by Administrator on 2017/5/14.
 */

public class SearchRecordSQHelper extends SQLiteOpenHelper {

    private static String name = "mysearch.db";
    private static Integer version = 1;

    public SearchRecordSQHelper(Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //Open the database and create a table called records, which contains only a list of name s to store historical records:
        db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

2. Instantiate this help class in oncreat e

    SearchRecordSQHelper helper = new SearchRecordSQHelper(this);
    //Actual requirements, access history is not displayed by default
    queryRecords("")

Query Records (String tempName) Query Data

 /*
     *Fuzzy query data and display on ListView list
     * */
    private void queryRecords(String tempName) {
            //Fuzzy Search
            Cursor cursor = helper.getReadableDatabase().rawQuery(
                    "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
            // Create adapter adapter object and load the results of fuzzy search
            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);
            list_result.setAdapter(adapter);
            adapter.notifyDataSetChanged();
    }

3. Enter keywords in EditText and click Search Query

 String et_text = et.getText().toString().toString().trim();
                if(et_text.length()==0){
                    return;
                }
                //Is there a history of isExistData, returning a Boolean value
                boolean is_existData = isExistData(et_text);
                if (!is_existData) {
                    insertRecords(et_text);//insert data
                    //After inserting data into the database, query the display data again. This is for testing. The real situation should jump directly to an interface.
                    queryRecords("");
                }
                //Fuzzy query results based on the input content and jump to another interface, which is implemented according to requirements.
                Toast.makeText(MainActivity.this,"Search results:"+et_text, Toast.LENGTH_SHORT).show();

Is there a history of isExistData, returning a Boolean value

 /**
     * Whether there is data, return boolean
     */
    private boolean isExistData(String tempName) {
        //Find the id of name=tempName from the record table
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //Judge if there's another one
        return cursor.moveToNext();
    }

Insert Records (et_text) insert data

 /*
     *insert data
     * */
    private void insertRecords(String tempName) {
        //History field: tempName
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

Enter the search interface again, input keywords, query the database dynamically, match the corresponding data and display it.

  • TextWatcher is used here to monitor the information input by edittext in real time.
//Each time you enter information in EditText, these three methods are invoked in turn
  et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //Call before text input

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            //Call in text input

            }

            @Override
            public void afterTextChanged(Editable s) {
             //Text Input Complete Call
            }
        });
  • Function implementation (input keywords, query data, display)
 @Override
    public void afterTextChanged(Editable s) {
        //Text Input Completes Call
        if (s.toString().trim().length() != 0) {
            list_result.setVisibility(View.VISIBLE);
            clearRecord.setVisibility(View.VISIBLE);
            serch_result.setVisibility(View.VISIBLE);
        }
        //After each input, the database is queried and displayed.
        //Fuzzy query whether there is data in the database according to the input value
        String tempName = et.getText().toString().trim();
        queryRecords(tempName);
    }

wipe data

 /**
     * wipe data
     */
    private void clearRecord() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

To basically complete here, what click events have not been written, this article mainly provides a train of thought, specific needs what functions, but also need to be customized according to the actual situation!

demo download: http://download.csdn.net/detail/qq_34501274/9842502

Keywords: Database Android

Added by pendragonf on Mon, 01 Jul 2019 03:39:30 +0300