How to implement type search bar functionality to find between multiple SQLite ListView items using EditText in android application.
This tutorial is one of the most advanced android application development tutorial because in this tutorial we would going implement Search Box Filter on local SQLite data. The filter is applied where all the data shows in ListView. The data is in multiple form means each column contains two values one is student name second is student phone Number. The search filter is designed using EditText So here is the complete step by step tutorial for Android Add Search Box Filter on Multiple SQLite Database Data.
Thing we have done in this project :
- Creating SQLite Database with table.
- Inserting records into SQLite Database using EditText.
- Showing SQLite data into ListView.
- Implement Search Box using EditText.
- Reverting search item clicked value.
Project File details :
List of all activity in this project :
- MainActivity.java
- SearchSQLiteActivity.java
List of all Java files in this project :
- SQLiteHelper.java
- ListAdapter.java
- Student.java
List of all layout files in this project :
- activity_main.xml
- activity_search_sqlite.xml
- custom_layout.xml
Watch live demo video to implement Search Box Filter :
Start Coding :
Code for MainActivity.java file.
package com.androidjson.searchsqlitedb_androidjsoncom; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { SQLiteDatabase sqLiteDatabase; Boolean EditTextEmptyHold; EditText getNAME, getPhoneNumber; Button SubmitData, ShowData; String name, phoneNumber, query; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SubmitData = (Button)findViewById(R.id.button); getPhoneNumber = (EditText)findViewById(R.id.editText2); ShowData = (Button)findViewById(R.id.button2); getNAME = (EditText)findViewById(R.id.editText); SubmitData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SQLiteDataBaseBuild(); SQLiteTableBuild(); CheckEditTextStatus(); InsertDataIntoSQLiteDatabase(); EmptyEditTextAfterDataInsert(); } }); ShowData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, SearchSQLiteActivity.class); startActivity(intent); } }); } public void SQLiteDataBaseBuild(){ sqLiteDatabase = openOrCreateDatabase(SQLiteHelper.DATABASE_NAME, Context.MODE_PRIVATE, null); } public void SQLiteTableBuild(){ sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+SQLiteHelper.TABLE_NAME+"("+SQLiteHelper.Table_Column_ID+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+SQLiteHelper.Table_Column_1_Name+" VARCHAR, "+SQLiteHelper.Table_Column_2_PhoneNumber+" VARCHAR);"); } public void CheckEditTextStatus(){ name = getNAME.getText().toString() ; phoneNumber = getPhoneNumber.getText().toString(); if(TextUtils.isEmpty(name) || TextUtils.isEmpty(phoneNumber)){ EditTextEmptyHold = false ; } else { EditTextEmptyHold = true ; } } public void InsertDataIntoSQLiteDatabase(){ if(EditTextEmptyHold == true) { query = "INSERT INTO "+SQLiteHelper.TABLE_NAME+" (name,phone_number) VALUES('"+name+"', '"+phoneNumber+"');"; sqLiteDatabase.execSQL(query); Toast.makeText(MainActivity.this,"Data Inserted Successfully", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this,"Please Fill All The Required Fields.", Toast.LENGTH_LONG).show(); } } public void EmptyEditTextAfterDataInsert(){ getNAME.getText().clear(); getPhoneNumber.getText().clear(); } }
Code for SearchSQLiteActivity.java file.
package com.androidjson.searchsqlitedb_androidjsoncom; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class SearchSQLiteActivity extends AppCompatActivity { ListView listView; ArrayList<Student> StudentList = new ArrayList<Student>(); ListAdapter listAdapter; SQLiteHelper sqLiteHelper; EditText editText; SQLiteDatabase sqLiteDatabase; Cursor cursor; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_sqlite); listView = (ListView) findViewById(R.id.listView1); editText = (EditText) findViewById(R.id.edittext1); listView.setTextFilterEnabled(true); sqLiteHelper = new SQLiteHelper(this); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Getting Search ListView clicked item. Student ListViewClickData = (Student) parent.getItemAtPosition(position); // printing clicked item on screen using Toast message. Toast.makeText(SearchSQLiteActivity.this, ListViewClickData.getName(), Toast.LENGTH_SHORT).show(); } }); editText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence stringVar, int start, int before, int count) { listAdapter.getFilter().filter(stringVar.toString()); } }); } public void DisplayDataInToListView() { sqLiteDatabase = sqLiteHelper.getWritableDatabase(); cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteHelper.TABLE_NAME+"", null); Student student; StudentList = new ArrayList<Student>(); if (cursor.moveToFirst()) { do { String tempName = cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table_Column_1_Name)); String tempNumber= cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table_Column_2_PhoneNumber)); student = new Student(tempName, tempNumber); StudentList.add(student); } while (cursor.moveToNext()); } listAdapter = new ListAdapter(SearchSQLiteActivity.this, R.layout.custom_layout, StudentList); listView.setAdapter(listAdapter); cursor.close(); } @Override protected void onResume() { DisplayDataInToListView() ; super.onResume(); } }
Code for SQLiteHelper.java file.
package com.androidjson.searchsqlitedb_androidjsoncom; /** * Created by Juned on 1/23/2017. */ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SQLiteHelper extends SQLiteOpenHelper { static String DATABASE_NAME="AndroidJSonDataBase"; public static final String TABLE_NAME="AndroidJSonTable"; public static final String Table_Column_ID="id"; public static final String Table_Column_1_Name="name"; public static final String Table_Column_2_PhoneNumber="phone_number"; public SQLiteHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase database) { String CREATE_TABLE="CREATE TABLE IF NOT EXISTS "+TABLE_NAME+" ("+Table_Column_ID+" INTEGER PRIMARY KEY, "+Table_Column_1_Name+" VARCHAR, "+Table_Column_2_PhoneNumber+" VARCHAR)"; database.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } }
Code for ListAdapter.java file.
package com.androidjson.searchsqlitedb_androidjsoncom; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.TextView; import java.util.ArrayList; /** * Created by Juned on 2/20/2017. */ public class ListAdapter extends ArrayAdapter<Student> { public ArrayList<Student> MainList; public ArrayList<Student> StudentListTemp; public ListAdapter.SubjectDataFilter studentDataFilter; public ListAdapter(Context context, int id, ArrayList<Student> studentArrayList) { super(context, id, studentArrayList); this.StudentListTemp = new ArrayList<Student>(); this.StudentListTemp.addAll(studentArrayList); this.MainList = new ArrayList<Student>(); this.MainList.addAll(studentArrayList); } @Override public Filter getFilter() { if (studentDataFilter == null) { studentDataFilter = new ListAdapter.SubjectDataFilter(); } return studentDataFilter; } public class ViewHolder { TextView Name; TextView Number; } @Override public View getView(int position, View convertView, ViewGroup parent) { ListAdapter.ViewHolder holder = null; if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.custom_layout, null); holder = new ListAdapter.ViewHolder(); holder.Name = (TextView) convertView.findViewById(R.id.textviewName); holder.Number = (TextView) convertView.findViewById(R.id.textviewPhoneNumber); convertView.setTag(holder); } else { holder = (ListAdapter.ViewHolder) convertView.getTag(); } Student student = StudentListTemp.get(position); holder.Name.setText(student.getName()); holder.Number.setText(student.getNumber()); return convertView; } private class SubjectDataFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence charSequence) { charSequence = charSequence.toString().toLowerCase(); FilterResults filterResults = new FilterResults(); if (charSequence != null && charSequence.toString().length() > 0) { ArrayList<Student> arrayList1 = new ArrayList<Student>(); for (int i = 0, l = MainList.size(); i < l; i++) { Student subject = MainList.get(i); if (subject.toString().toLowerCase().contains(charSequence)) arrayList1.add(subject); } filterResults.count = arrayList1.size(); filterResults.values = arrayList1; } else { synchronized (this) { filterResults.values = MainList; filterResults.count = MainList.size(); } } return filterResults; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { StudentListTemp = (ArrayList<Student>) filterResults.values; notifyDataSetChanged(); clear(); for (int i = 0, l = StudentListTemp.size(); i < l; i++) add(StudentListTemp.get(i)); notifyDataSetInvalidated(); } } }
Code for Student.java file.
package com.androidjson.searchsqlitedb_androidjsoncom; /** * Created by Juned on 2/21/2017. */ public class Student { String name = null; String number = null; public Student(String Sname, String Snumber) { super(); this.name = Sname; this.number = Snumber; } public String getName() { return name; } public void setName(String Name2) { this.name = Name2; } public String getNumber() { return number; } public void setNumber(String number2) { this.number = number2; } @Override public String toString() { return name + " " + number ; } }
Code for activity_main.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.androidjson.searchsqlitedb_androidjsoncom.MainActivity"> <TextView android:text="Insert Records in SQLite Database" android:layout_width="wrap_content" android:gravity="center" android:textSize="21dp" android:textColor="#000000" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:id="@+id/textView"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="Enter Name Here" android:layout_centerHorizontal="true" android:gravity="center" android:ems="10" android:layout_marginTop="27dp" android:id="@+id/editText" android:layout_below="@+id/textView"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone" android:hint="Enter Phone Number Here" android:id="@+id/editText2" android:gravity="center" android:ems="10" android:layout_below="@+id/editText" android:layout_centerHorizontal="true" android:layout_marginTop="36dp"/> <Button android:text="Click Here to Insert" android:layout_width="fill_parent" android:layout_marginTop="46dp" android:layout_height="wrap_content" android:layout_below="@+id/editText2" android:layout_centerHorizontal="true" android:id="@+id/button" /> <Button android:text="Show records with search bar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/button2" android:layout_below="@+id/button" android:layout_centerHorizontal="true" android:layout_marginTop="11dp"/> </RelativeLayout>
Code for activity_search_sqlite.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_search_sqlite" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.androidjson.searchsqlitedb_androidjsoncom.SearchSQLiteActivity"> <EditText android:id="@+id/edittext1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:hint="Search Here" > </EditText> <ListView android:id="@+id/listView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/edittext1"/> </RelativeLayout>
Code for custom_layout.xml layout file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textviewName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Subject Name" android:textSize="25dp" android:textColor="#000000" /> <TextView android:id="@+id/textviewPhoneNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textviewName" android:text="Subject Full Form" android:layout_below="@+id/textviewName" android:textSize="20dp" android:textColor="#000000" /> </RelativeLayout>
Screenshots: