How to implement ListView search function in app using EditText and show only entered element after filter adapter.
In this tutorial we would going to implement Search Functionality to JSON ListView by using EditText. Firstly we would create ListView using JSON data, coming from online MySQL database, present on our hosting server. Now we would convert that MySQL data into JSON form using PHP Script. Now we would parse that data into our app and create ListView. After that using EditText addTextChangedListener() method we would filer the ListView and show the filter result. So here is the complete step by step tutorial for Android Add Search Functionality to Custom JSON ListView Adapter.
Follow the below steps :
1. Create a database on your PhpMyAdmin .
2. Inside that database create a table named as SubjectsTable with two columns id and subject_Name . Below is the screenshot of table after inserting few records.
3. Upload the PHP script on you server that convert the MySQL data into JSON. There are two files in this project First one is DatabaseConfig.php file which contain database authentication details like host name, password etc. Second file is all_subjects.php file which convert the SQL data into JSON.
Code for DatabaseConfig.php file.
<?php //Define your host here. $HostName = "localhost"; //Define your database username here. $HostUser = "id302300_android_examples_data_user"; //Define your database password here. $HostPass = "1234567890"; //Define your database name here. $DatabaseName = "id302300_android_examples"; ?>
Code for all_subjects.php file.
<?php include 'DatabaseConfig.php'; // Create connection $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM SubjectsTable"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $tem = $row; $json = json_encode($tem); } } else { echo "No Results Found."; } echo $json; $conn->close(); ?>
4. Start a new android application project in Android Studio.
5. Add Internet permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
6. Add / Import useLibrary ‘org.apache.http.legacy’ inside build.gradle(Module:app) file . So open build.gradle(Module:app) file.
7. Add useLibrary ‘org.apache.http.legacy’ inside the android block.
How to Add Search Functionality to Custom JSON ListView Adapter App source code starts from here :
Code for MainActivity.java file.
package com.android_examples.searchfilterlistview_android_examplescom; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.os.AsyncTask; import android.widget.Toast; import android.widget.AdapterView; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.text.Editable; import android.widget.ListView; import android.text.TextWatcher; import android.view.View; import android.widget.ProgressBar; import android.widget.ArrayAdapter; import android.widget.EditText; public class MainActivity extends AppCompatActivity { ListView listView; ProgressBar progressBar; String HTTP_JSON_URL = "https://android-examples.000webhostapp.com/all_subjects.php"; EditText editText ; List SubjectArrayList = new ArrayList(); ArrayAdapter arrayAdapter ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.listview1); progressBar = (ProgressBar)findViewById(R.id.progressBar); editText = (EditText)findViewById(R.id.edittext1); // Calling Method to Parese JSON data into listView. new GetHttpResponse(MainActivity.this).execute(); // Calling EditText addTextChangedListener method which controls the EditText type sequence. editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { //Updating Array Adapter ListView after typing inside EditText. MainActivity.this.arrayAdapter.getFilter().filter(charSequence); } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { } }); // Adding On item click listener on ListView. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub String Item = parent.getItemAtPosition(position).toString(); // Showing ListView click item using Toast message on screen. Toast.makeText(MainActivity.this, Item, Toast.LENGTH_LONG).show(); } }); } // Creating GetHttpResponse message to parse JSON. public class GetHttpResponse extends AsyncTask<Void, Void, Void> { // Creating context. public Context context; // Creating string to hold Http response result. String ResultHolder; // Creating constructor . public GetHttpResponse(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... arg0) { // Sending the Http URL into HttpServicesClass to parse JSON. HttpServicesClass httpServiceObject = new HttpServicesClass(HTTP_JSON_URL); try { httpServiceObject.ExecutePostRequest(); // If the server response code = 200 then JSON parsing start. if(httpServiceObject.getResponseCode() == 200) { // Adding Http response into ResultHolder string. ResultHolder = httpServiceObject.getResponse(); // If there is response present into ResultHolder. if(ResultHolder != null) { // Creating JSONArray and set it to null. JSONArray jsonArray = null; try { // Adding ResultHolder into JSONArray. jsonArray = new JSONArray(ResultHolder); // Creating JSONObject. JSONObject jsonObject; // Starting for loop at the end of jsonArray length. for(int i=0; i<jsonArray.length(); i++) { // Adding JSON array object . jsonObject = jsonArray.getJSONObject(i); // Adding the JSON parse object into SubjectArrayList. SubjectArrayList.add(jsonObject.getString("subject_Name").toString()) ; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { // If something goes wrong then showing the error message on screen. Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // This block will execute after done all background processing. @Override protected void onPostExecute(Void result) { // Hiding the progress bar after done loading JSON. progressBar.setVisibility(View.GONE); // Showing the ListView after done loading JSON. listView.setVisibility(View.VISIBLE); // Setting up the SubjectArrayList into Array Adapter. arrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_2, android.R.id.text1, SubjectArrayList); // Passing the Array Adapter into ListView. listView.setAdapter(arrayAdapter); } } }
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:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.android_examples.searchfilterlistview_android_examplescom.MainActivity"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/edittext1" android:hint="Search Here" android:gravity="center"/> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="visible" /> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview1" android:layout_below="@id/edittext1" /> </RelativeLayout>
Code for HttpServicesClass.java file.