In this tutorial we will create an Android Spinner Example Application. So the first thing probably you are thinking is What is Spinner? Actually Spinner is used to show a dropdown list. So in this Android Spinner Example Tutorial we will create a spinner. And in the spinner we will show the values from MySQL database.
Android Spinner Example Video
Before going further you can check out this video to see the final output of the app we are creating.
Now if you wanna create the same, lets begin this Android Spinner Example Tutorial. So in this tutorial we will retrieve data from our webserver using JSON String. I have my URL that will give me a JSON string by fetching values from MySQL database.
http://simplifiedcoding.16mb.com/Spinner/json.php
The above link will give us the following json string.
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 |
{ "result":[ { "username":"faiz", "name":"Faiz Khan", "course":"BCA", "session":"2014-2017" }, { "username":"belal", "name":"Belal Khan", "course":"MCA", "session":"2015-2018" }, { "username":"ramiz", "name":"Ramiz Khan", "course":"MBA", "session":"2015-2017" }, { "username":"zafar", "name":"Zafar Khan", "course":"MBA", "session":"2014-2016" } ] } |
You can create your own url or you can also use mine. Lets move to Android Studio now.
Creating Android Spinner Example Application
- Open Android Studio and create new Project.
- For this tutorial we will use volley library so add the following code in you build.gradle dependencies
1 2 3 4 5 6 7 8 9 10 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.0' //Volley Library compile 'com.mcxiaoke.volley:library-aar:1.0.0' } |
- Now sync your project with gradle.
- Come to activity_main.xml and create the following layout.
- In the above layout we have a Spinner and 3 TextViews. When user will select an item from the Spinner the details will be shown to the TextView.
- You can use the following xml code for creating the above layout. Define Spinner and 3 TextViews.
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spinner" /> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_marginRight="20dp" android:layout_marginLeft="10dp" android:text="Name" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_marginRight="20dp" android:text="Course" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_marginRight="20dp" android:text="Session" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:layout_marginLeft="10dp" android:id="@+id/textViewName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:id="@+id/textViewCourse" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:id="@+id/textViewSession" /> </TableRow> </TableLayout> </LinearLayout> |
- Create a class named Config.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package net.simplifiedcoding.spinnerexample; /** * Created by Belal on 10/31/2015. */ public class Config { //JSON URL public static final String DATA_URL = "http://simplifiedcoding.16mb.com/Spinner/json.php"; //Tags used in the JSON String public static final String TAG_USERNAME = "username"; public static final String TAG_NAME = "name"; public static final String TAG_COURSE = "course"; public static final String TAG_SESSION = "session"; //JSON array name public static final String JSON_ARRAY = "result"; } |
- Now come to MainActivity.java and write the following code.
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 |
package net.simplifiedcoding.spinnerexample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; 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; public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{ //Declaring an Spinner private Spinner spinner; //An ArrayList for Spinner Items private ArrayList<String> students; //JSON Array private JSONArray result; //TextViews to display details private TextView textViewName; private TextView textViewCourse; private TextView textViewSession; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initializing the ArrayList students = new ArrayList<String>(); //Initializing Spinner spinner = (Spinner) findViewById(R.id.spinner); //Adding an Item Selected Listener to our Spinner //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener spinner.setOnItemSelectedListener(this); //Initializing TextViews textViewName = (TextView) findViewById(R.id.textViewName); textViewCourse = (TextView) findViewById(R.id.textViewCourse); textViewSession = (TextView) findViewById(R.id.textViewSession); //This method will fetch the data from the URL getData(); } private void getData(){ //Creating a string request StringRequest stringRequest = new StringRequest(Config.DATA_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { JSONObject j = null; 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(Config.JSON_ARRAY); //Calling method getStudents to get the students from the JSON Array getStudents(result); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); //Creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(this); //Adding request to the queue requestQueue.add(stringRequest); } private void getStudents(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 students.add(json.getString(Config.TAG_USERNAME)); } catch (JSONException e) { e.printStackTrace(); } } //Setting adapter to show the items in the spinner spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students)); } //Method to get student name of a particular position private String getName(int position){ String name=""; try { //Getting object of given index JSONObject json = result.getJSONObject(position); //Fetching name from that object name = json.getString(Config.TAG_NAME); } catch (JSONException e) { e.printStackTrace(); } //Returning the name return name; } //Doing the same with this method as we did with getName() private String getCourse(int position){ String course=""; try { JSONObject json = result.getJSONObject(position); course = json.getString(Config.TAG_COURSE); } catch (JSONException e) { e.printStackTrace(); } return course; } //Doing the same with this method as we did with getName() private String getSession(int position){ String session=""; try { JSONObject json = result.getJSONObject(position); session = json.getString(Config.TAG_SESSION); } catch (JSONException e) { e.printStackTrace(); } return session; } //this method will execute when we pic an item from the spinner @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //Setting the values to textviews for a selected item textViewName.setText(getName(position)); textViewCourse.setText(getCourse(position)); textViewSession.setText(getSession(position)); } //When no item is selected this method would execute @Override public void onNothingSelected(AdapterView<?> parent) { textViewName.setText(""); textViewCourse.setText(""); textViewSession.setText(""); } } |
- Finally before running this Android Spinner Example , add internet permission to your manifest file.
1 2 3 |
<uses-permission android:name="android.permission.INTERNET"/> |
- Now run your application.
- Bingo! Our Android Spinner Example App is working absolutely fine. You can also download my source code from below.
Get source of Android Spinner Example
[sociallocker id=1372] [download id=”1467″]Â [/sociallocker]
So thats all for this Android Spinner Example Tutorial friend. This was a very simple android spinner example. Please do comment if you are having any trouble or queries. Thank You 🙂