
Hello Friends, Today we’ll see an example of SearchView Suggestions over Network in Android. And there will be two part of this code one will be server side code in PHP and another one Android app code. Actually I was working on an android app in which I was required to add search suggestion over network feature in that, So now I am sharing this sample code almost same as I have developed for the app just to help others and me in future projects. If you want to know how to use SearchView in toolbar before proceeding with suggestion over network you can checkout this post.
Let’s code now without wasting any time..
Server Side PHP Code
config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php date_default_timezone_set("Asia/Kolkata"); define("DATABASE_NAME", "YOUR-DB-NAME"); function getConnection() { $servername = "localhost"; $username = "YOUR-USERNAME"; $password = "YOUR-PASSWORD"; // Create connection $conn = new mysqli($servername, $username, $password, DATABASE_NAME); // Check connection if (mysqli_connect_error()) { die("Database connection failed: " . mysqli_connect_error()); } else { return $conn; } } define("KEY", "SECUREKEY"); |
api.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php include_once 'config.php'; header("Content-Type:application/json"); if (!isset($_REQUEST['key']) || trim($_REQUEST['key']) != KEY) { die("Not authorised"); } if (!isset($_REQUEST['action'])) { echo "Please provide action parameter"; die(); } $action = trim($_REQUEST['action']); if ($action == 'get-search-suggestions') { $conn = getConnection(); //check get parameter or request parameter or post parameter and respond accordingly if (isset($_REQUEST['term'])) { $term = filter_var(trim($_REQUEST['term']), FILTER_SANITIZE_STRING); $results = $conn->query("SELECT id, name, color, size, price FROM items WHERE name LIKE '%{$term}%' OR color LIKE '%{$term}%' OR size LIKE '%{$term}%' OR price LIKE '%{$term}%' LIMIT 5"); echo $conn->error; $suggestions = array(); while ($row = $results->fetch_assoc()) { $suggestions[] = $row; } respond("200", "Search Suggestions", $suggestions); exit(); } } function respond($status, $status_message, $data) { header("HTTP/1.1 $status $status_message"); $response['status'] = $status; $response['status_message'] = $status_message; $response['data'] = $data; echo json_encode($response); } |
Android App Code
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
package com.zatackcoder.searchviewsuggestionsovernetwork; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SearchView; import androidx.recyclerview.widget.RecyclerView; import android.app.SearchManager; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.os.AsyncTask; import android.os.Bundle; import android.provider.BaseColumns; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity { private SuggestionAdapter suggestionAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_main_activity, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchManager searchManager = (SearchManager) getApplicationContext().getSystemService(Context.SEARCH_SERVICE); SearchView searchView = null; if (searchItem != null) { searchView = (SearchView) searchItem.getActionView(); } if (searchView != null) { searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName())); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { return true; } @Override public boolean onQueryTextChange(String s) { new GetSuggestionsAsyncTask(MainActivity.this, s).execute(); return false; } }); suggestionAdapter = new SuggestionAdapter(getApplicationContext(), null, false); searchView.setSuggestionsAdapter(suggestionAdapter); } return super.onCreateOptionsMenu(menu); } static class GetSuggestionsAsyncTask extends AsyncTask<Void, Void, Cursor> { private final WeakReference<MainActivity> activityReference; final String term; GetSuggestionsAsyncTask(MainActivity context, String term) { this.activityReference = new WeakReference<>(context); this.term = term; } @Override protected Cursor doInBackground(Void... voids) { HashMap<String, String> params = new HashMap<>(); params.put("key", "SECUREKEY"); params.put("action", "get-search-suggestions"); params.put("term", term); JsonParser jsonParser = new JsonParser(); JSONObject jsonObject = jsonParser.get("https://zatackcoder.com/demo/searchview-suggestion-over-network/api.php", params); MatrixCursor cursor = new MatrixCursor(new String[]{BaseColumns._ID, "name", "color", "size", "price"}); if (jsonObject != null) { try { JSONArray dataJsonArray = jsonObject.getJSONArray("data"); int j = 0; for (int i = 0; i < dataJsonArray.length(); i++) { JSONObject tmp = dataJsonArray.getJSONObject(i); String[] row = {Integer.toString(j++), tmp.getString("name"), tmp.getString("color"), tmp.getString("size"), tmp.getString("price")}; cursor.addRow(row); } } catch (JSONException e) { e.printStackTrace(); } } return cursor; } @Override protected void onPostExecute(Cursor cursor) { super.onPostExecute(cursor); MainActivity mainActivity = activityReference.get(); if(mainActivity == null || mainActivity.isFinishing()) { return; } mainActivity.suggestionAdapter.changeCursor(cursor); } } } |
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SearchView Suggestion Over Network Example" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
JsonParser.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
package com.zatackcoder.searchviewsuggestionsovernetwork; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; /** * Created by rajesh kumar sahanee on 19/9/17. */ public class JsonParser { private final String TAG = "JsonParser"; private HttpURLConnection conn; private final StringBuilder result = new StringBuilder(); private JSONObject jsonObject; public JSONObject post(String url, HashMap<String, String> params, HashMap<String, String> files) { try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoInput(true);//Allow Inputs conn.setDoOutput(true);//Allow Outputs conn.setUseCaches(false);//Don't use a cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setReadTimeout(10000); conn.setConnectTimeout(50000); String boundary = "*****"; if (files != null) { conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); for (String key : files.keySet()) { conn.setRequestProperty(key, files.get(key)); } } conn.connect(); DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream()); //file uploading String twoHyphens = "--"; String lineEnd = "\r\n"; if (files != null) { for (String key : files.keySet()) { int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; //1 * 1024 * 1024 File selectedFile = new File(files.get(key)); if (!selectedFile.isFile()) { break; } dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); //writing bytes to data outputstream dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\";filename=\"" + files.get(key) + "\"" + lineEnd); dataOutputStream.writeBytes(lineEnd); FileInputStream fileInputStream = new FileInputStream(selectedFile); //returns no. of bytes present in fileInputStream bytesAvailable = fileInputStream.available(); //selecting the buffer size as minimum of available bytes or 1 MB bufferSize = Math.min(bytesAvailable, maxBufferSize); //setting the buffer as byte array of size of bufferSize buffer = new byte[bufferSize]; //reads bytes from FileInputStream(from 0th index of buffer to buffersize) bytesRead = fileInputStream.read(buffer, 0, bufferSize); //loop repeats till bytesRead = -1, i.e., no bytes are left to read while (bytesRead > 0) { //write the bytes read from inputstream dataOutputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dataOutputStream.writeBytes(lineEnd); dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); fileInputStream.close(); } } //parameters writing when file uploading if (params != null && files != null) { for (String key : params.keySet()) { dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd); dataOutputStream.writeBytes(lineEnd); dataOutputStream.writeBytes(params.get(key)); dataOutputStream.writeBytes(lineEnd); dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); } } //parameters writing when no file uploading else if (params != null) { StringBuilder psb = new StringBuilder(); boolean flag = false; for (String key : params.keySet()) { try { if (flag) { psb.append("&"); } psb.append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } flag = true; } dataOutputStream.writeBytes(psb.toString()); } Log.d(TAG, "RC: " + conn.getResponseCode() + " RM: " + conn.getResponseMessage()); dataOutputStream.flush(); dataOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { //Receive the response from the server BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream()))); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d(TAG, "Result: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); // try parse the string to a JSON object try { jsonObject = new JSONObject(result.toString()); } catch (JSONException e) { Log.e(TAG, "Error parsing data " + e.toString()); } // return JSON Object return jsonObject; } public JSONObject get(String url, HashMap<String, String> params) { StringBuilder psb = new StringBuilder(); boolean flag = false; for (String key : params.keySet()) { if (flag) { psb.append("&"); } try { psb.append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } flag = true; } if (psb.length() != 0) { url += "?" + psb.toString(); Log.d(TAG, "url: " + url); } try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setConnectTimeout(15000); conn.connect(); } catch (IOException e) { e.printStackTrace(); } try { //Receive the response from the server BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream()))); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d(TAG, "Result: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); // try parse the string to a JSON object try { jsonObject = new JSONObject(result.toString()); } catch (JSONException e) { Log.e(TAG, "Error parsing data " + e.toString()); } // return JSON Object return jsonObject; } } |
SuggestionAdapter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.zatackcoder.searchviewsuggestionsovernetwork; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.cursoradapter.widget.CursorAdapter; public class SuggestionAdapter extends CursorAdapter { public SuggestionAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.search_view_suggestion, parent, false); } @Override public void bindView(View view, final Context context, Cursor cursor) { TextView nameTV = view.findViewById(R.id.nameTV); TextView descTV = view.findViewById(R.id.descTV); if(cursor.getColumnIndex("name") != -1 && cursor.getString(cursor.getColumnIndex("name")) != null) { final String name = cursor.getString(cursor.getColumnIndex("name")); String color = cursor.getString(cursor.getColumnIndex("color")); String size = cursor.getString(cursor.getColumnIndex("size")); String price = cursor.getString(cursor.getColumnIndex("price")); nameTV.setText(name); descTV.setText(String.format("color:%s size%s price:%s", color, size, price)); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "You Just Clicked " + name, Toast.LENGTH_LONG).show(); } }); } } } |
search_view_suggestion.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/white" android:padding="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackground" android:orientation="horizontal"> <ImageView android:id="@+id/imageIV" android:layout_width="36dp" android:layout_height="36dp" android:layout_marginEnd="2dp" android:layout_marginRight="2dp" app:srcCompat="@android:drawable/ic_menu_search" android:src="@android:drawable/ic_menu_search"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/nameTV" android:layout_width="match_parent" android:layout_height="wrap_content" android:ellipsize="end" android:lines="1" android:maxLines="1" android:textSize="14sp" /> <TextView android:id="@+id/descTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textAlignment="center" android:textSize="12sp" /> </LinearLayout> </LinearLayout> </RelativeLayout> |
menu/menu_main_activity.xml
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_search" android:icon="@android:drawable/ic_menu_search" android:title="Search" app:actionViewClass="androidx.appcompat.widget.SearchView" app:showAsAction="always|collapseActionView" /> </menu> |
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zatackcoder.searchviewsuggestionsovernetwork"> <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> |
Video
PHP Script Download

SearchView Suggestions over Network PHP Script
1 file(s) 1.56 KB
Android Studio Project Download

SearchViewSuggestionsOverNetwork Android Studio Project
1 file(s) 9.45 MB
Thanks for Stoping by
If you find this helpful then please do share
Any suggestions and queries are welcome in comment section
Comments