0

Android Add Search Functionality to Custom JSON ListView Adapter

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.

JSON_Table

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.

package com.android_examples.searchfilterlistview_android_examplescom;

/**
 * Created by Juned on 5/21/2017.
 */

import org.apache.http.HttpEntity;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.NameValuePair;
import java.io.BufferedReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.ClientProtocolException;
import java.net.URLEncoder;
import java.util.ArrayList;

public class HttpServicesClass {
    public int responseCode;

    public String message;

    public String response;

    public ArrayList<NameValuePair> ArrayListParams;

    public ArrayList <NameValuePair> headers;

    public String UrlHolder;

    public String getResponse()
    {
        return response;
    }

    public String getErrorMessage()
    {
        return message;
    }

    public int getResponseCode()
    {
        return responseCode;
    }

    public HttpServicesClass(String url)
    {
        HttpServicesClass.this.UrlHolder = url;

        ArrayListParams = new ArrayList<NameValuePair>();

        headers = new ArrayList<NameValuePair>();
    }

    public void AddParam(String name, String value)
    {
        ArrayListParams.add(new BasicNameValuePair(name, value));
    }

    public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void ExecuteGetRequest() throws Exception
    {
        String MixParams = "";

        if(!ArrayListParams.isEmpty())
        {
            MixParams += "?";

            for(NameValuePair p : ArrayListParams)
            {
                String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");

                if(MixParams.length() > 1)
                {
                    MixParams  +=  "&" + paramString;
                }
                else
                {
                    MixParams += paramString;
                }
            }
        }

        HttpGet httpGet = new HttpGet(UrlHolder + MixParams);

        for(NameValuePair h : headers)
        {
            httpGet.addHeader(h.getName(), h.getValue());
        }

        executeRequest(httpGet, UrlHolder);
    }

    public void ExecutePostRequest() throws Exception
    {
        HttpPost httpPost = new HttpPost(UrlHolder);
        for(NameValuePair h : headers)
        {
            httpPost.addHeader(h.getName(), h.getValue());
        }

        if(!ArrayListParams.isEmpty())
        {
            httpPost.setEntity(new UrlEncodedFormEntity(ArrayListParams, HTTP.UTF_8));
        }

        executeRequest(httpPost, UrlHolder);
    }

    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpParams httpParameters = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);

        HttpConnectionParams.setSoTimeout(httpParameters, 10000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);

        HttpResponse httpResponse;
        try
        {
            httpResponse = httpClient.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null)
            {
                InputStream inputStream = entity.getContent();

                response = convertStreamToString(inputStream);

                inputStream.close();
            }
        }
        catch (ClientProtocolException e)
        {
            httpClient.getConnectionManager().shutdown();
            e.printStackTrace();
        }
        catch (IOException e)
        {
            httpClient.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream is)
    {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

        StringBuilder stringBuilder = new StringBuilder();

        String line = null;
        try
        {
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line + "\n");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

}

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android_examples.searchfilterlistview_android_examplescom">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots :-

Android Add Search Functionality to Custom JSON ListView Adapter

Click here to download project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *