There are many online tutorials in this area, think about it or decide to write down my own code, in order to facilitate future review.
Look at the picture first.
Implement the following functions
1. Addition, deletion and alteration of database
2. Searched keywords will not be added to the database again
3. Click records can be added to the search box
XML layout file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:orientation="vertical" tools:context=".SearchActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:id="@+id/search_et_search" android:layout_width="match_parent" android:layout_height="35dp" android:layout_marginRight="2dp" android:background="@drawable/et_style_search" android:hint=" search " android:drawableLeft="@drawable/search" android:paddingLeft="5dp" android:singleLine="true" android:layout_weight="1" /> <ImageView android:id="@+id/voice_iv" android:layout_width="25dp" android:layout_height="30dp" android:src="@drawable/voice" android:layout_gravity="center" android:layout_marginRight="5dp" /> <TextView android:id="@+id/cancel_tv_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="cancel" android:textSize="20sp" android:textColor="#257bf4" /> </LinearLayout> <ListView android:id="@+id/search_record_iv" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> <View android:layout_width="match_parent" android:layout_height="0.05dp" android:background="#4a949393"/> <TextView android:id="@+id/clearReocrds_tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:textAlignment="center" android:visibility="gone" android:text="Clear up historical records" android:textSize="12sp" /> </LinearLayout>
Java code
1,
public class RecordsSQLiteOpenHelper extends SQLiteOpenHelper { //Declare a string representing the database name private final static String DB_NAME = "MyRecords.db"; //Declare an integer variable representing the database version private static int DB_VERSION = 1; public RecordsSQLiteOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { //Establishment of records tables String sql = "CREATE TABLE IF NOT EXISTS records (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
2. Inherit the ArrayAdapter class and write the RecordsAdapter adapter class
public class RecordsAdapter extends ArrayAdapter { //Define an integer that records the id of the text that displays the record private int resourceId; public RecordsAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) { super(context, resource, objects); resourceId = resource; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view = LayoutInflater.from(getContext()).inflate(resourceId,null); //Instantiate an object TextView showRecord = (TextView)view.findViewById(R.id.search_content_tv); String record = (String)getItem(position); //Gets the current record string showRecord.setText(record); return view; } }
3. Writing Search Record Operating Class
/** * Search Record Operations Class * Various operations for encapsulation of search records */ public class RecordsDao { RecordsSQLiteOpenHelper recordHelper; //Define an Operational Help Object for a Database SQLiteDatabase recordDb; //Define a recorded database object public RecordsDao(Context context){ recordHelper = new RecordsSQLiteOpenHelper(context); } /** * This function is used to add search records */ public void addRecords(String record){ if (!isHasRecord(record)){ //Determine whether the record exists in the source data recordDb = recordHelper.getWritableDatabase(); //Getting Search Records Database ContentValues value = new ContentValues(); value.put("name",record); recordDb.insert("records",null,value); //insert record recordDb.close(); } } /** * This function is used to retrieve all search records * @return List<String> */ public List<String> getRecordsList(){ List<String> recordsList = new ArrayList<String>(); recordDb = recordHelper.getReadableDatabase(); Cursor cursor = recordDb.query("records",null,null,null,null,null,null); while (cursor.moveToNext()){ String record = cursor.getString(cursor.getColumnIndexOrThrow("name")); recordsList.add(record); } recordDb.close(); cursor.close(); return recordsList; } /** * This function is used to empty search records */ public void clearRecords(){ String sql = "delete from records"; recordDb = recordHelper.getWritableDatabase(); recordDb.execSQL(sql); recordDb.close(); } /** * This function is used for fuzzy query */ public List<String> querySimilarRecords(String record){ String sql = "select * from records where name like'%" + record + "%' order by name"; // String queryStr = "select * from records where name like '%" + record + "%' order by name "; List<String> similarRecordsList = new ArrayList<String>(); recordDb = recordHelper.getReadableDatabase(); Cursor cursor = recordDb.rawQuery(sql,null); while (cursor.moveToNext()){ String myRecord = cursor.getString(cursor.getColumnIndexOrThrow("name")); similarRecordsList.add(myRecord); } recordDb.close(); cursor.close(); return similarRecordsList; } /** * This function is used to determine whether the record exists in the original database. * @return Recorded return true */ private boolean isHasRecord(String record){ boolean isHasRecord = false; recordDb = recordHelper.getReadableDatabase(); Cursor cursor = recordDb.query("records",null,null,null,null,null,null); while (cursor.moveToNext()){ if (record.equals(cursor.getString(cursor.getColumnIndexOrThrow("name")))){ isHasRecord = true; break; } } recordDb.close(); cursor.close(); return isHasRecord; } }
4. Next is the code in MainActivity. I implemented this part of the function in a project I practiced. The code is very complicated. Here's the key code
recordsDao = new RecordsDao(SearchActivity.this);
/** * Binder Adapter */ void bindAdapter(){ recordsList = recordsDao.getRecordsList(); //An array for retrieving search records reversedRecords(); ckeckRecords(); //Check for records recordsAdapter = new RecordsAdapter(SearchActivity.this,R.layout.listview_item,recordsList); records_lv.setAdapter(recordsAdapter); }
/** * This function is used to reverse search records */ private void reversedRecords(){ String temp = ""; int size = (recordsList.size())/2; int foot = recordsList.size()-1; //The following loop implements the array head-and-tail permutation for (int i=0;i<size;i++){ foot = foot - i; temp = recordsList.get(i); recordsList.set(i,recordsList.get(foot)); recordsList.set(foot,temp); } }
/** * Create a listener object for the History List * Click on the record to add it to the search box */ AdapterView.OnItemClickListener lvListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String myClicked = recordsList.get(position); search_et.setText(myClicked); } };
/** * Create a "Clear History" listener object */ View.OnClickListener clearListener = new View.OnClickListener() { @Override public void onClick(View v) { recordsList.clear(); recordsDao.clearRecords(); recordsAdapter.notifyDataSetChanged(); ckeckRecords(); } };
There are many details of the above code that have not been released. There are still some functions that have not been implemented, such as: monitoring the soft keyboard return button set to the search button, using TextWatcher() for real-time filtering, and so on.
More detailed code refers to the articles of these two gods
Android - Simple Use of ListView and Customized ListView Interface
Simple Implementation of Android Search Function to Display and Clear History Search Records