How to add filter functionality on multiple JSON ListView items coming from online MySQL database server in android example tutorial.
Searching is the most common way to find your preferred item between multiple items. If there is a ListView containing thousands of records and you need to find you own record in between them you need to use search box . So in this tutorial we would going to create an android application with one EditText and ListView. The ListView is just placed under the EditText and ListView contains real time JSON data. When user starts typing into EditText then it will start filtering the JSON listview data at real time and update the ListView again with new filtered data. So here is the complete step by step tutorial for Android Implement Filter Using Search Box on JSON ListView Tutorial.
Follow the below steps :
1. Create MySQL database on your hosting server.
2. Create a table in database named as SubjectFullFormTable . The table contain three columns id, SubjectName, and SubjectFullForm . Below is the screenshot of table :
3. Next step is to create and upload PHP script that would convert the MySQL database data into JSON format.
Code for DatabaseConfig.php file.
<?php //Define your host here. $HostName = "localhost"; //Define your database username here. $HostUser = "id632449_androidjson"; //Define your database password here. $HostPass = "kdfjdfdskljomew9ry3873"; //Define your database name here. $DatabaseName = "id632449_androidjson"; ?>
Code for SubjectFullForm.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 SubjectFullFormTable"; $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 development project.
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.
Android Implement Filter Using Search Box on JSON ListView Tutorial.
Code for MainActivity.java file.
package com.androidjson.searchlistviewmultiple_androidjsoncom; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.ArrayList; import android.content.Context; 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.ProgressBar; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { ListView listView; EditText editText; ArrayList<Subject> SubjectList = new ArrayList<Subject>(); String HttpURL = "https://androidjsonblog.000webhostapp.com/SubjectFullForm.php"; ListAdapter listAdapter; ProgressBar progressBar ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView1); editText = (EditText) findViewById(R.id.edittext1); progressBar = (ProgressBar)findViewById(R.id.progressbar); listView.setTextFilterEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Subject ListViewClickData = (Subject)parent.getItemAtPosition(position); Toast.makeText(MainActivity.this, ListViewClickData.getSubName(), 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()); } }); new ParseJSonDataClass(this).execute(); } private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> { public Context context; String FinalJSonResult; public ParseJSonDataClass(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... arg0) { HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL); try { httpServiceClass.ExecutePostRequest(); if (httpServiceClass.getResponseCode() == 200) { FinalJSonResult = httpServiceClass.getResponse(); if (FinalJSonResult != null) { JSONArray jsonArray = null; try { jsonArray = new JSONArray(FinalJSonResult); JSONObject jsonObject; Subject subject; SubjectList = new ArrayList<Subject>(); for (int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); String tempName = jsonObject.getString("SubjectName").toString(); String tempFullForm = jsonObject.getString("SubjectFullForm").toString(); subject = new Subject(tempName, tempFullForm); SubjectList.add(subject); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { progressBar.setVisibility(View.INVISIBLE); listAdapter = new ListAdapter(MainActivity.this, R.layout.custom_layout, SubjectList); listView.setAdapter(listAdapter); } } }
Code for HttpServiceClass.java file.
package com.androidjson.searchlistviewmultiple_androidjsoncom; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.ArrayList; /** * Created by Juned on 1/30/2017. */ public class HttpServiceClass { private ArrayList<NameValuePair> params; private ArrayList<NameValuePair> headers; private String url; private int responseCode; private String message; private String response; public String getResponse() { return response; } public String getErrorMessage() { return message; } public int getResponseCode() { return responseCode; } public HttpServiceClass(String url) { this.url = url; params = new ArrayList<NameValuePair>(); headers = new ArrayList<NameValuePair>(); } public void AddParam(String name, String value) { params.add(new BasicNameValuePair(name, value)); } public void AddHeader(String name, String value) { headers.add(new BasicNameValuePair(name, value)); } public void ExecuteGetRequest() throws Exception { String combinedParams = ""; if (!params.isEmpty()) { combinedParams += "?"; for (NameValuePair p : params) { String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8"); if (combinedParams.length() > 1) { combinedParams += "&" + paramString; } else { combinedParams += paramString; } } } HttpGet request = new HttpGet(url + combinedParams); for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url); } public void ExecutePostRequest() throws Exception { HttpPost request = new HttpPost(url); for (NameValuePair h : headers) { request.addHeader(h.getName(), h.getValue()); } if (!params.isEmpty()) { request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } executeRequest(request, url); } private void executeRequest(HttpUriRequest request, String url) { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 10000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient client = new DefaultHttpClient(httpParameters); HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
Code for ListAdapter.java file.