
Android Cascading Spinner – In this post we will see how we can populate second spinner dynamically based on selection of first spinner. We will select a category from first spinner then we will fetch data from mysql database according to the selected category.So let’s start with php, mysql part.
Installing XAMPP Server
Before do anything firstly check you have XAMPP Server on your system. Alternatively you can use WAMP (For Windows), LAMP (For Linux) and MAMP (For MAC).
If you don’t have XAMPP Server you can Download and Install form https://www.apachefriends.org/download.html
Start Apache and Mysql form XAMPP Control Panel.
Creating MySql Database
In this tutorial to demonstrate we will take two Spinners. First Spinner is for loading Mobile Names and Second for to load Mobile Model Names of that Mobile which we selected from first spinner.
Open phpmyadmin to open this type localhost/phpmyadmin in Internet Browser and Create a Database and Table.
Creating Database
1 |
CREATE DATABASE mobile; |
Creating model table
1 2 3 4 5 6 |
CREATE TABLE IF NOT EXISTS `model` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `mobile` varchar(10) NOT NULL, `model` varchar(50) NOT NULL, PRIMARY KEY (`uid`) ); |
Inserting Data
1 2 3 4 5 6 7 8 9 10 11 |
INSERT INTO `model` (`mobile`, `model`) VALUES ('Samsung', 'Galaxy S7'), ('Samsung', 'Galaxy S7 Edge'), ('Apple', 'iphone 7'), ('Xiaomi', 'MI Note 4'), ('Xiaomi', 'MI 4'), ('Samsung', 'Note 8'), ('Samsung', 'A8+'), ('Apple', 'iphone 7 Plus'), ('Apple', 'iphone x'), ('Xiaomi', 'MI Y1'); |
Creating PHP Files
In this part we will create 3 files.
- config.php – This file will have Database Name, Username and Password.
- DbConnect.php – A class to open and close the database connection.
- get_model.php – To fetch Model Name of Mobiles from Database.
Open htdocs folder under C:\xampp and Create folder CascedingSpinner .In this folder create file-
- config.php- In this file we mentioned database name, username, password and host name. If your mysql database is having a password, don’t forget to define it here.
12345678<?php//Database configurationdefine('DB_USERNAME', 'root');define('DB_PASSWORD', '');define('DB_HOST', 'localhost');define('DB_NAME', 'mobile');?> - DbConnect.php – A class to open and close the database connection.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849<?php// Connecting disconnecting Databaseclass DbConnect {private $conn;// constructorfunction __construct() {// connecting to database$this->connect();}// destructorfunction __destruct() {// closing db connection$this->close();}/*** Establishing database connection* @return database handler*/function connect() {include_once dirname(__FILE__) . '/config.php';// Connecting to mysql database$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());// Selecting databasemysql_select_db(DB_NAME) or die(mysql_error());// returing connection resourcereturn $this->conn;}/*** Closing database connection*/function close() {// closing db connectionmysql_close($this->conn);}}?> - get_model.php – Here we simply open the database connection, catch Mobile Name from Query String , run a select query and build a response array and echo the json.
12345678910111213141516171819202122232425262728293031<?phpinclude_once './DbConnect.php';function getModel(){$db = new DbConnect();// array for json response$response = array();$response["model"] = array();$mobile=$_GET['mobile'];// Mysql select query$result = mysql_query("SELECT * FROM model WHERE mobile='$mobile'");while($row = mysql_fetch_array($result)){// temporary array to create single category$tmp = array();$tmp["model"] = $row["model"];// push category to final json arrayarray_push($response["model"], $tmp);}// keeping response header to jsonheader('Content-Type: application/json');// echoing json resultecho json_encode($response);}getModel();?>
We are done with server side part. Let’s move to Android Part.
Creating New Android Project – Android Cascading Spineer
- Create a new project in Android Studio File–>New–>New Project.
- Enter Application Name, Package Name, Select Empty Activity and click on finish.
- Add library in app build.gradle file –
1useLibrary 'org.apache.http.legacy' - Our application will use Internet to access data so firstly we need to add INTERNET permission in AndroidManifest.xml file. Open your AndroidManifest.xml file and add following permission.<uses-permission android:name=”android.permission.INTERNET”/>
123456789101112131415161718192021222324<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.androidcodefinder.cascadingspinners"><!-- Internet Permissions --><uses-permission android:name="android.permission.INTERNET"/><applicationandroid: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> - Create a class file named Model.java. This model class will be useful to convert json data into objects.
12345678910111213141516171819202122232425package com.androidcodefinder.cascadingspinners;/*** Created by Sumeet Jain on 18-12-2017.*/public class Model {private String model;public Model(){}public Model(String model){this.model = model;}public void setModel(String model){this.model = model;}public String getModel(){return this.model;}} - Create a class named Handler.java and write the following code. makeServiceCall() method should be called to make http calls.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106package com.androidcodefinder.cascadingspinners;import android.util.Log;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.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.utils.URLEncodedUtils;import org.apache.http.impl.client.DefaultHttpClient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.List;public class Handler {static InputStream is = null;static String response = null;public final static int GET = 1;public final static int POST = 2;public Handler() {}/*** Making service call* @url - url to make request* @method - http request method* */public String makeServiceCall(String url, int method) {return this.makeServiceCall(url, method, null);}/*** Making service call* @url - url to make request* @method - http request method* @params - http request params* */public String makeServiceCall(String url, int method,List<NameValuePair> params) {try {// http clientDefaultHttpClient httpClient = new DefaultHttpClient();HttpEntity httpEntity = null;HttpResponse httpResponse = null;// Checking http request method typeif (method == POST) {HttpPost httpPost = new HttpPost(url);// adding post paramsif (params != null) {httpPost.setEntity(new UrlEncodedFormEntity(params));}httpResponse = httpClient.execute(httpPost);} else if (method == GET) {// appending params to urlif (params != null) {String paramString = URLEncodedUtils.format(params, "utf-8");url += "?" + paramString;}HttpGet httpGet = new HttpGet(url);httpResponse = httpClient.execute(httpGet);}httpEntity = httpResponse.getEntity();is = httpEntity.getContent();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}try {BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);StringBuilder sb = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {sb.append(line + "\n");}is.close();response = sb.toString();} catch (Exception e) {Log.e("Buffer Error", "Error: " + e.toString());}return response;}} - Open Values–>Strings.xml file and put values for arrary.
1 2 3 4 5 6 7 8 |
<resources> <string name="app_name">CascadingSpinners</string> <string-array name="mobile_arrays"> <item>Apple</item> <item>Samsung</item> <item>Xiaomi</item> </string-array> </resources> |
- Now we will design the interface for our main activity. We have two Spinners on our layout first will load Mobile name and a Second spinner to show the Model Name fetched from MySQL database. Open activity_main.xml file and insert the following code.
1234567891011121314151617181920212223242526272829303132333435363738394041<?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"><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="vertical"android:id="@+id/linearLayout"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Select Mobile-"android:textSize="16dp"android:layout_marginLeft="4dp"/><Spinnerstyle="@style/Widget.AppCompat.DropDownItem.Spinner"android:layout_width="fill_parent"android:layout_height="50dp"android:id="@+id/spinnerMobile"android:entries="@array/mobile_arrays"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Select Model-"android:textSize="16dp"android:layout_marginLeft="4dp"/><Spinnerstyle="@style/Widget.AppCompat.DropDownItem.Spinner"android:layout_width="fill_parent"android:layout_height="50dp"android:id="@+id/spinnerModel"/></LinearLayout></RelativeLayout> - Open your MainActivity.java file add the basic code like declaring required variables, spinner listener etc. we defined an Async method to fetch list of Model Name from MySQL and showing them in spinner. Add the following code after onCreate block in MainActivity.java. I also added another method populateSpinnerModel() to takes care of loading the data into spinner. This async method should be called in onCreate method like new GetModelFromServer().execute(). complete code of 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 118 119 120 121 122 123 124 125 |
package com.androidcodefinder.cascadingspinners; import android.app.ProgressDialog; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Spinner spinnerMobile,spinnerModel; Button buttonSubmit; ProgressDialog pDialog; private String mobileName; // array list for spinner adapter private ArrayList<Model> modelList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinnerMobile= (Spinner)findViewById(R.id.spinnerMobile); spinnerModel=(Spinner)findViewById(R.id.spinnerModel); modelList = new ArrayList<Model>(); spinnerMobile.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Refresh Spinner modelList.clear(); new GetModelFromServer().execute(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private class GetModelFromServer extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Fetching Data"); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { mobileName = spinnerMobile.getSelectedItem().toString(); Handler jsonParser = new Handler(); String json = jsonParser.makeServiceCall("http://192.168.1.5/cascedingspinner/get_model.php?mobile="+mobileName, Handler.GET); Log.e("Response: ", "> " + json); if (json != null) { try { JSONObject jsonObj = new JSONObject(json); if (jsonObj != null) { JSONArray model = jsonObj .getJSONArray("model"); for (int i = 0; i < model.length(); i++) { JSONObject modObj = (JSONObject) model.get(i); Model mod = new Model(modObj.getString("model")); modelList.add(mod); } } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("JSON Data", "Didn't receive any data from server!"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (pDialog.isShowing()) pDialog.dismiss(); populateSpinnerModel(); } } private void populateSpinnerModel() { List<String> lables = new ArrayList<String>(); for (int i = 0; i < modelList.size(); i++) { lables.add(modelList.get(i).getModel()); } // Creating adapter for spinner ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lables); // Drop down layout style - list view with radio button spinnerAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner spinnerModel.setAdapter(spinnerAdapter); } } |
Screen Shot
Download Source Code
Subscribe To Our YouTube Channel
Like Us On Facebook
how do you pass your params into database request by using post method?
Here i am using Get method. I will upload post on how you can pass params using post method as soon as possible .
error:
android:entries=”@array/mobile_arrays”/>
and if I removed that no data displayed in the dropdown….
Please add values of array in values–>strings.xml file
<%resources>
<%string name="app_name">CascadingSpinners<%/string>
<%string-array name="mobile_arrays">
<%item>Apple<%/item >
<%item>Samsung<%/item>
<%item>Xiaomi<%/item>
<%/string-array>
<%/resources>
Remove % before use
And how can I do it if I need two tables not juste one and the value of the first spinner based on the second one?