SearchView Suggestions over Network in Android Android Php by Rajesh Kumar Sahanee - May 24, 20200 Post Views: 5,542 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 config.php PHP <?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"); 123456789101112131415161718192021 <?phpdate_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 api.php PHP <?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); } 12345678910111213141516171819202122232425262728293031323334353637 <?phpinclude_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 MainActivity.java Java 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); } } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 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 activity_main.xml XHTML <?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> 123456789101112131415161718 <?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 JsonParser.java 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; } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228 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 SuggestionAdapter.java Java 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(); } }); } } } 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 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 search_view_suggestion.xml XHTML <?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> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 <?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 menu/menu_main_activity.xml XHTML <?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> 12345678910 <?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 AndroidManifest.xml XHTML <?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> 1234567891011121314151617181920212223 <?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 https://zatackcoder.com/wp-content/uploads/2020/05/SearchViewSuggestionsOverNetwork.mp4 PHP Script Download SearchView Suggestions over Network PHP Script 1 file(s) 1.56 KB Download Android Studio Project Download SearchViewSuggestionsOverNetwork Android Studio Project 1 file(s) 9.45 MB Download Thanks for Stoping by If you find this helpful then please do share Any suggestions and queries are welcome in comment section