Android Spinner Searchable With Search Box WITH Mysql Database values
Hey, Developers!
This Tutorial will teach you how to implement a spinner with inbuilt search functionality. Here we have taken a small example where on choosing one item from the Spinner, a statement about the item selected will appear in Toast.
Hey, Developers!
This Tutorial will teach you how to implement a spinner with inbuilt search functionality. Here we have taken a small example where on choosing one item from the Spinner, a statement about the item selected will appear in Toast.
Step 1. Defining Dependencies FOR spinner
I am going to use this github library in this example.
So add the following line in your build.gradle(Module:app) file
implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
Step 2. Layout
Add the following coding lines in activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" android:gravity="center" android:orientation="vertical" android:padding="10dp"> <ImageView android:id="@+id/imageView3" android:layout_width="match_parent" android:layout_height="70dp" android:src="@drawable/checkmark" app:srcCompat="@drawable/checkmark" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="PICK CITY" android:textSize="18sp" android:textStyle="bold" /> <com.toptoche.searchablespinnerlibrary.SearchableSpinner android:id="@+id/society_name" style="@android:style/Widget.Holo.Light.Spinner" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:id="@+id/subLinearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/textView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="PICK LOCATION" android:textSize="18sp" android:textStyle="bold" /> <com.toptoche.searchablespinnerlibrary.SearchableSpinner android:id="@+id/society_wingID" style="@android:style/Widget.Holo.Light.Spinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> </LinearLayout> <Button android:id="@+id/next" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimaryLight" android:text="Next" android:textColor="@color/sendotp_grey" /> </LinearLayout></ScrollView>Step 3. Final Change
Let us make a last change to make searchable spinner.Write down the below coding lines in MainActivity.java filepackage nanoakhi.city; /** * Created by NanoAkhi on 26-Oct-18. */ import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import dmax.dialog.SpotsDialog; import nanoakhi.bookmyparlour.R; import static nanoakhi.Config.CITY_URL;//UR JSON URL U NEED TO CREATE UR SELF import static nanoakhi.Config.SUBCITY_URL; public class city_subCity extends AppCompatActivity implements Spinner.OnItemSelectedListener { String WING, subcity_code, MEMBERSHIP_TYPE, DEPARTMENT; String societ_no_from_society_name, wing_no_from_wing_name, city_code, WINGID, DEPTCODENO; //Declaring an Spinner private Spinner society_name, society_wingID, society_flat, dept; Button next; EditText name; //JSON Array private JSONArray result, resultW, resultF; String registration_no, Society_Name, CITY; AlertDialog SocietyName, pDialogWing = null; AlertDialog pDialog, WingDialog = null; ArrayAdapter<String> adapterW, adapterF; //An ArrayList for Spinner Items private ArrayList<String> society_name_array; private ArrayList<String> wing_name; String NAME; Bundle bundle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.city_subcity); //SOCIETY NAME FETCHING HERE //Initializing the ArrayList society_name_array = new ArrayList<String>(); society_name = (Spinner) findViewById(R.id.society_name); society_name.setOnItemSelectedListener(this); //This method will fetch the data from the URL //CLASS LIST getSocietyName(); //Initializing the ArrayList wing_name = new ArrayList<String>(); society_wingID = (Spinner) findViewById(R.id.society_wingID); //WING NAME FETCHING HERE society_wingID.setOnItemSelectedListener(this); next = (Button) findViewById(R.id.next); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } //////SOCIETY NAME list method private void getSocietyName() { //Creating a string request SocietyName = new SpotsDialog(city_subCity.this); SocietyName.show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, CITY_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { JSONObject j = null; hideSocietyName(); try { //Parsing the fetched Json String to JSON Object j = new JSONObject(response); //Storing the Array of JSON String to our JSON Array result = j.getJSONArray("result"); //Calling method getsociety_name to get the society_name from the JSON Array getsociety_name(result); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { hideSocietyName(); } }); //Creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(city_subCity.this); //Adding request to the queue requestQueue.add(stringRequest); } private void getsociety_name(JSONArray j) { //Traversing through all the items in the json array for (int i = 0; i < j.length(); i++) { try { //Getting json object JSONObject json = j.getJSONObject(i); //Adding the name of the student to array list society_name_array.add(json.getString("main_city_name")); } catch (JSONException e) { e.printStackTrace(); } } //Setting adapter to show the items in the spinner society_name.setPrompt("Select "); society_name.setAdapter(new ArrayAdapter<String>(city_subCity.this, android.R.layout.simple_spinner_dropdown_item, society_name_array)); } //Doing the same with this method as we did with getName() private String getRLY_TYPE(int position) { String RLY_TYPE = ""; try { JSONObject json = result.getJSONObject(position); RLY_TYPE = json.getString("main_city_code"); } catch (JSONException e) { e.printStackTrace(); } return RLY_TYPE; } //////////////////Wing No Parsing private void getWing() { //societ_no_from_society_name = Output_Society_No.getText().toString(); societ_no_from_society_name = registration_no; WingDialog = new SpotsDialog(city_subCity.this); WingDialog.show(); // Showing progress dialog before making http request StringRequest stringRequest = new StringRequest(Request.Method.POST, SUBCITY_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { WingDialoghidePDialog(); JSONObject j = null; hidePDialogWing(); try { //Parsing the fetched Json String to JSON Object j = new JSONObject(response); //Storing the Array of JSON String to our JSON Array resultW = j.getJSONArray("result"); //Calling method getsociety_name to get the society_name from the JSON Array getwing_name(resultW); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { WingDialoghidePDialog(); } }) { @Override protected Map<String, String> getParams() { //PASSING STRING VALUE TO THE TAGGING PARAMETER WITH TENDS TO GO FOR TBALE NAME Map<String, String> params = new HashMap<String, String>(); // params.put(KEY_teacher_id,T_ID); params.put("main_city_code", city_code); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } private void getwing_name(JSONArray j) { //Traversing through all the items in the json array for (int i = 0; i < j.length(); i++) { try { //Getting json object JSONObject json = j.getJSONObject(i); //Adding the name of the student to array list wing_name.add(json.getString("city_name")); } catch (JSONException e) { e.printStackTrace(); } } //Setting adapter to show the items in the spinner society_wingID.setPrompt("Select "); adapterW = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, wing_name); adapterW.notifyDataSetChanged(); society_wingID.setAdapter(adapterW); } private String getsubcity_code(int position) { String subcity_code = ""; try { JSONObject json = resultW.getJSONObject(position); subcity_code = json.getString("city_code"); Log.d("subcity_code", "getsubcity_code: " + subcity_code); } catch (JSONException e) { e.printStackTrace(); } return subcity_code; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { parent.getItemAtPosition(position); switch (parent.getId()) { case R.id.society_name: // getRLY_TYPE(position); // city_code = society_name.getSelectedItem().toString(); city_code = getRLY_TYPE(position); wing_name.clear(); getWing(); break; case R.id.society_wingID: WING = society_wingID.getSelectedItem().toString(); subcity_code= getsubcity_code(position); Toast.makeText(this, subcity_code, Toast.LENGTH_SHORT).show(); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } @Override public void onDestroy() { super.onDestroy(); hidePDialog(); hideSocietyName(); hidePDialogWing(); WingDialoghidePDialog(); } private void WingDialoghidePDialog() { if (WingDialog != null) { WingDialog.dismiss(); WingDialog = null; } } private void hideSocietyName() { if (SocietyName != null) { SocietyName.dismiss(); SocietyName = null; } } private void hidePDialogWing() { if (pDialogWing != null) { pDialogWing.dismiss(); pDialogWing = null; } } private void hidePDialog() { if (pDialog != null) { pDialog.dismiss(); pDialog = null; } } }JSON GENERATED WILL BE LIKE THIS:{"result":[{"city_code":"DDN_SPE","city_name":"Dehra Dun Direction-Sharanpur Road","main_city_code":"DDN"},{"city_code":"DDN_MUSS","city_name":"Dehra Dun Direction-Mussoorie","main_city_code":"DDN"},{"city_code":"DDN_HW","city_name":"Dehra Dun Direction-Raipur\/Haridwar","main_city_code":"DDN"},{"city_code":"DDN_PN","city_name":"Dehra Dun Direction-Prem Nagar\/Selaqui","main_city_code":"DDN"},{"city_code":"DDN_CEN","city_name":"Dehra Dun Central","main_city_code":"DDN"}]}
- When user have selects a specific options then compiler will call onItemSelected()method.
- If user do not choose any option then compiler will call onNothingSelected()method.
- onItemSelected() method will simply show a toast that will say that which value is selected by the user.
Thus, we have make searchable spinner with very little coding lines.
IF U HAVE DOUBT CONTACT ME
akhileshnanoakhi@gmail.com
Post a Comment
0Comments