Fundamentals
Introduction
1st Android Application

OOPS Concepts
Class
Object
Abstraction
Encapsulation

Polymorphism
Inheritance
Message Passing
Dynamic Binding

UI Controls
TextView
Button
Toggle Button
CheckBox
Radio Button
Spinner
ProgressBar
SeekBar
RadioGroup
RatingBar
Switch
EditText
AutoComplete
TextView

MultiAutoComplete
TextView

ImageView
ImageButton
Gallery
MediaPlayer
VideoView
MediaController

TimePicker
DatePicker
CalendarView
Chronometer
Analog Clock
Digital Clock

Layouts
LinearLayout
RelativeLayout
GridLayout
TableLayout
FrameLayout
Fragment

Composite
ListView
ExpandableListView
GridView
ScrollView
SearchView
Sliding Drawer
Tab Widget
WebView

Transitions
Image Switcher
StackView
TextSwitcher
ViewAnimator
View Flipper
View Switcher

Advanced
Request Focus
View
View Stub
TextureView
Gesture Overlay View

SurfaceView
NumberPicker
Zoom Button
Zoom Controls
AbsoluteLayout

Database
SharedPreference
SQLite DB
MySQL DB

Webservices
Check HttpURLConnection
Single Webservice Call
Multi Webservice Call
ListView from Webservice
SQLite from Webservice
Data from Database

Telephone Manager
IMEI
IMSI
Phone Type
Sim Type
Network Type

Content Providers
Contact Provider
BookMark Provider
Own Provider


Message & Networking
Send SMS
SMS with Reports
Group SMS

Send E-Mail
Download Binary Data


Location Based Service
Display Google Map
Events with Google Map

Android Services
Create Service
Create Longtime Service

Asynchronous Task
Repeating Services
IntentService

Activity from a Service
Bind Activity to Service


Sample Projects
HMS
CNB
Login Screen
Camera Event
Browse Option
QR Code Events
Accelerometer Sensor
EditText from Spinner

Android Spinner

  1. Static Spinner Creation in Android
  2. Dynamic Spinner Creation in Android
  3. Create More Spinner in More Ways
  4. Update Spinner from MySQL Database
  5. Dependant Spinners from MySQL Database
  6. Transparent Spinner without using Alpha
  7. Spinner with Previously Selected Value
  8. Sort Spinner Items in Android
  9. Run Time Add Item to Spinner
  10. Spinners from EditText
  11. Spinner Selection defines Item for Another Spinner

Note                     Download ADT Plugin Here.
Here I am using,
OS : Linux (Ubuntu 12.04)
Eclipse : Juno (Version 4.2.0)
Android API Level : 3 to 'n' as per need
Emulator API Level : It will be displayed in output image

A. Static Spinner Creation in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <TextView
        android:id="@+id/textView1"
        android:textSize="20dp"
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="Static Spinner" />
 
    <Spinner
        android:id="@+id/spinner1"
        android:entries="@array/spinner_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_static;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
 
public class MainActivity extends Activity {
 
	Spinner sp;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        sp = (Spinner) findViewById(R.id.spinner1);
        
        sp.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
				
			Toast.makeText(getBaseContext(), sp.getSelectedItem().toString(), 
				Toast.LENGTH_SHORT).show();
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_static"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Static</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    
    <string-array name = "spinner_item">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
        <item>Item 4</item>
        <item>Item 5</item>
    </string-array>
 
</resources>

Step 6 : Our output will be like this :


Output


Output









B. Dynamic Spinner Creation in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <TextView
        android:id="@+id/textView1"
        android:textSize="20dp"
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="Dynamic Spinner" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_dynamic;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
	RelativeLayout rl;
	Spinner sp;
	List<String> list;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        rl = (RelativeLayout) findViewById(R.id.rl);
        sp = new Spinner (MainActivity.this);
        
        list = new ArrayList<String> ();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
        list.add("Item 5");
        
        ArrayAdapter<String> adp = new ArrayAdapter<String> 
        (this,android.R.layout.simple_dropdown_item_1line, list);
        sp.setAdapter(adp);
        
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams
        		((int) LayoutParams.WRAP_CONTENT, (int) LayoutParams.WRAP_CONTENT);
        params.leftMargin = 170;
        params.topMargin = 150;
        
        sp.setLayoutParams(params);
        
        
        rl.addView(sp);
        
        sp.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
				
			Toast.makeText(getBaseContext(), list.get(arg2).toString(), 
				Toast.LENGTH_SHORT).show();
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_dynamic"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Dynamic</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output


Output









C. Create More Spinner in More Ways


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="40dp" />
 
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40dp"
        android:layout_centerHorizontal="true" />
 
    <Spinner
        android:id="@+id/spinner3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="40dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_more;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
	Spinner sp1, sp2, sp3;
	List<String> list;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        sp1 = (Spinner) findViewById(R.id.spinner1);
        sp2 = (Spinner) findViewById(R.id.spinner2);
        sp3 = (Spinner) findViewById(R.id.spinner3);
        
        list = new ArrayList<String> ();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
        list.add("Item 5");
        
        final String[] str1={"Report 1","Report 2","Report 3","Report 4","Report 5"};
        
        ArrayAdapter<String> adp1 = new ArrayAdapter<String> 
        (this, android.R.layout.simple_dropdown_item_1line, list);
        
        ArrayAdapter<String> adp2 = new ArrayAdapter<String> 
        (this, android.R.layout.simple_dropdown_item_1line, str1);
        
        ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource
        		(this, R.array.str2, android.R.layout.simple_dropdown_item_1line);
        
        sp1.setAdapter(adp1);
        sp2.setAdapter(adp2);
        sp3.setAdapter(adp3);
        
        sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
				
			Toast.makeText(getBaseContext(), list.get(arg2),
				Toast.LENGTH_SHORT).show();
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
        
        sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
				
			Toast.makeText(getBaseContext(), str1[arg2],
				Toast.LENGTH_SHORT).show();
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
        
        sp3.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
				
			String item = sp3.getSelectedItem().toString();
			Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_more"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_More</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
    <string-array name="str2">
	    <item>Data 1</item>
	    <item>Data 2</item>
	    <item>Data 3</item>
	    <item>Data 4</item>
	    <item>Data 5</item>
	    </string-array>
    
</resources>

Step 6 : Our output will be like this :


Output


Output


Output


Output









D. Update Spinner from MySQL Database


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Create a Database and Table like below :


Output


Step 3 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="98dp" />
 
</RelativeLayout>

Step 4 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_update_mysql_db;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
 
public class MainActivity extends Activity {
	
	InputStream is=null;
	String result=null;
	String line=null;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        try
        {
        	HttpClient httpclient = new DefaultHttpClient();
        	HttpPost httppost = new HttpPost("http://10.0.2.2/spinner.php");
        	HttpResponse response = httpclient.execute(httppost); 
        	HttpEntity entity = response.getEntity();
        	is = entity.getContent();
        	Log.e("Pass 1", "connection success ");
        }
        catch(Exception e)
        {
        	Log.e("Fail 1", e.toString());
        	Toast.makeText(getApplicationContext(), "Invalid IP Address",
			Toast.LENGTH_LONG).show();
        }     
 
        try
        {
        	BufferedReader reader = new BufferedReader
			(new InputStreamReader(is,"iso-8859-1"),8);

        	StringBuilder sb = new StringBuilder();
        	
        	while ((line = reader.readLine()) != null)
        	{
        		sb.append(line + "\n");
        	}
        	
        	is.close();
        	result = sb.toString();
        	Log.e("Pass 2", "connection success ");
        }
        catch(Exception e)
        {
        	Log.e("Fail 2", e.toString());
        }     
 
        try
        {
        	JSONArray JA=new JSONArray(result);
        	JSONObject json= null;
        	final String[] str1 = new String[JA.length()];        
        	final String[] str2 = new String[JA.length()];
        	
        	for(int i=0;i<JA.length();i++)
        	{
        		json=JA.getJSONObject(i);
        		str1[i] = json.getString("roll_no");
        		str2[i]=json.getString("name");
        	}

        	final Spinner sp = (Spinner) findViewById(R.id.spinner1);
        	List<String> list = new ArrayList<String>();
        	
        	for(int i=0;i<str2.length;i++)
        	{
        		list.add(str2[i]);
        	}
 
        	Collections.sort(list);
 
        	ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
			(getApplicationContext(), android.R.layout.simple_spinner_item, list);
        	dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        	sp.setAdapter(dataAdapter);
 
        	sp.setOnItemSelectedListener(new OnItemSelectedListener() 
        	{
        		public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id) 
        		{
        			// TODO Auto-generated method stub

        			String item=sp.getSelectedItem().toString();

        			Toast.makeText(getApplicationContext(), item,
					Toast.LENGTH_LONG).show();

        			Log.e("Item",item);
        		}
 
        		public void onNothingSelected(AdapterView<?> arg0) 
        		{
        			// TODO Auto-generated method stub
        		}
        	});
        }
        catch(Exception e)
        {
        	Log.e("Fail 3", e.toString());
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Step 5 : Open spinner.php and add following code :

<?php
	$host='127.0.0.1';
	$uname='root';
	$pwd='password';
	$db='android';

	$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
	mysql_select_db($db,$con) or die("db selection failed");

	$r=mysql_query("select * from class",$con);

	while($row=mysql_fetch_array($r))
	{
		$cls[]=$row;
	}

	print(json_encode($cls));
	mysql_close($con);
?>

Step 6 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_update_mysql_db"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 7 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Update_MySql_DB</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 8 : Our output will be like this :


Output


Output









E. Dependant Spinners from MySQL Database


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
    
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="100dp" />
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="10dp" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="Proceed" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_dependant_db;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
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 android.widget.AdapterView.OnItemSelectedListener;
 
public class MainActivity extends Activity {
 
    InputStream is=null;
    String result=null;
    String line=null;
    String[] roll_no,name;   
    Spinner spinner1,spinner2;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	spinner1 = (Spinner) findViewById(R.id.spinner1);
	spinner2 = (Spinner) findViewById(R.id.spinner2);
	final List<String> list1 = new ArrayList<String>();
	final List<String> list2 = new ArrayList<String>();

	Button b=(Button) findViewById(R.id.button1);
 
	b.setOnClickListener(new View.OnClickListener() {
	
		public void onClick(View v) 
		{
			// TODO Auto-generated method stub

			try
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://10.0.2.2/spinner.php");
				HttpResponse response = httpclient.execute(httppost); 
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				Log.e("Pass 1", "connection success ");
			}
			catch(Exception e)
			{
				Log.e("Fail 1", e.toString());
				Toast.makeText(getApplicationContext(), "Invalid IP Address",
					Toast.LENGTH_LONG).show();
				finish();
			}     

			try
			{
				BufferedReader reader = new BufferedReader
					(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				
				while ((line = reader.readLine()) != null)
				{
					sb.append(line + "\n");
				}
				
				is.close();
				result = sb.toString();
			}
			catch(Exception e)
			{
				Log.e("Fail 2", e.toString());
			}    

			try
			{
				JSONArray JA=new JSONArray(result);
				JSONObject json= null;
				roll_no = new String[JA.length()];        
				name = new String[JA.length()];
 
				for(int i=0;i<JA.length();i++)
				{
					json=JA.getJSONObject(i);
					roll_no[i] = json.getString("roll_no");
					name[i]=json.getString("name");
				}
 
				for(int i=0;i<roll_no.length;i++)
				{
					list1.add(roll_no[i]);
					list2.add(name[i]);
				}

				spinner_fn();
			}
			catch(Exception e)
			{
				Log.e("Fail 3", e.toString());
				//login.this.finish();
			}
		}
	});
    }
    
    private void spinner_fn() {
	// TODO Auto-generated method stub

	ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
			android.R.layout.simple_spinner_item, roll_no);
	dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	spinner1.setAdapter(dataAdapter1);

	ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getApplicationContext(),
			android.R.layout.simple_spinner_item, name);
	dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	spinner2.setAdapter(dataAdapter2);

	spinner1.setOnItemSelectedListener(new OnItemSelectedListener() 
	{
		public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id) 
		{
			// TODO Auto-generated method stub

			spinner2.setSelection(position);
		}
		public void onNothingSelected(AdapterView<?> arg0) 
		{
			// TODO Auto-generated method stub
		}
	});

	spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
			// TODO Auto-generated method stub

			spinner1.setSelection(position);
		}
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	});
    }

    public boolean onCreateOptionsMenu(Menu menu) {
	getMenuInflater().inflate(R.menu.activity_main, menu);
	return true;
    }
}

Step 4 : Open spinner.php and add following code :

<?php
	$host='127.0.0.1';
	$uname='root';
	$pwd='password';
	$db='android';

	$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
	mysql_select_db($db,$con) or die("db selection failed");

	$r=mysql_query("select * from class",$con);

	while($row=mysql_fetch_array($r))
	{

		$cls[]=$row;

	}

	print(json_encode($cls));
	mysql_close($con);
?>

Step 5 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_dependant_db"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 6 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Dependant_DB</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 7 : Our output will be like this :


Output


Output


Output


Output


Output









F. Transparent Spinner without using Alpha


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="76dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_transparent_without_alpha;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
 
public class MainActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final List<String> list=new ArrayList<String>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
        list.add("Item 5");
 
        Spinner sp1= (Spinner) findViewById(R.id.spinner1);
        RelativeLayout rl=(RelativeLayout) findViewById(R.id.rl);
        int clr= rl.getDrawingCacheBackgroundColor();
        
        sp1.setBackgroundColor(clr);
        ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
        		android.R.layout.simple_list_item_1,list);
        adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp1.setAdapter(adp);
        
        sp1.setOnItemSelectedListener(new OnItemSelectedListener()
        {
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int position, long id) {
			// TODO Auto-generated method stub
				
			Toast.makeText(getBaseContext(), list.get(position),
				Toast.LENGTH_SHORT).show();
		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_transparent_without_alpha"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Transparent_without_Alpha</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output


Output


Output









G. Spinner with Previously Selected Value


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="96dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_previously_selected_value;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
	private SharedPreferences prefs;
	private String prefName = "spinner_value"; 
	int id=0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final List<String> list=new ArrayList<String>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
        list.add("Item 5");
        
        final Spinner sp=(Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<String> adp= new ArrayAdapter<String>(this,
        		android.R.layout.simple_list_item_1,list);
        adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(adp);
        
        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        id=prefs.getInt("last_val",0);
        sp.setSelection(id);
        
        sp.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int pos, long arg3) {
			// TODO Auto-generated method stub
				
			prefs = getSharedPreferences(prefName, MODE_PRIVATE);
			SharedPreferences.Editor editor = prefs.edit();
		
			//---save the values in the EditText view to preferences---
		 	editor.putInt("last_val", pos);
		       
			//---saves the values---
		 	editor.commit();
		
			Toast.makeText(getBaseContext(), sp.getSelectedItem().toString(),
				Toast.LENGTH_SHORT).show();
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_previously_selected_value"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Previously_Selected_Value</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output


Output


Step 7 : Close and Re-Execute the Application. Our Spinner output will be like this :


Output









H. Sort Spinner Items in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="86dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_sort_item;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
 
public class MainActivity extends Activity {
 
	int position=0;
	String val=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final Spinner sp=(Spinner) findViewById(R.id.spinner1);
        
        final List<String> list=new ArrayList<String> ();
 
        list.add("A");
        list.add("V");
        list.add("Z");
        list.add("S");
        list.add("F");
        list.add("Q");
        list.add("E");
        list.add("G");
        list.add("H");
        list.add("K");
        
        // Sort List Items
        Collections.sort(list);
        
        final ArrayAdapter<String> adp= new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,list);
	adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	sp.setAdapter(adp);
	
	sp.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int pos, long arg3) {
			// TODO Auto-generated method stub
				
			position=pos;
			val=sp.getSelectedItem().toString();
			// You can insert your code...				
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_sort_item"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Sort_Item</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output









I. Run Time Add Item to Spinner


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:hint="Enter your Item"
        android:ems="10" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp"
        android:text="Add" />
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_run_time_add_item;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
 
public class MainActivity extends Activity {
 
	Spinner sp;
	EditText et;
	List<String> li;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        li=new ArrayList<String>();
        li.add("Item 1");
        li.add("Item 2");
        li.add("Item 3");
        
        sp=(Spinner) findViewById(R.id.spinner1);
        Button b=(Button) findViewById(R.id.button1);
        et=(EditText)findViewById(R.id.editText1);
        
        add();
        
        b.setOnClickListener(new View.OnClickListener() {
			
		public void onClick(View v) {
			// TODO Auto-generated method stub
				
			li.add(et.getText().toString());
			et.setText(null);
			add();
		}
	});
    }
 
    private void add() {
		// TODO Auto-generated method stub
		ArrayAdapter<String> adp=new ArrayAdapter<String>(this, 
				android.R.layout.simple_dropdown_item_1line,li);
		sp.setAdapter(adp);
	}
 
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_run_time_add_item"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Run_Time_Add_Item</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output


Output


Output









J. Spinners from EditText


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <EditText
        android:id="@+id/editText1"
        android:hint="Enter Items"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:ems="10" >
 
        <requestFocus />
    </EditText>
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:text="Proceed" />
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="40dp"/>
 
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="40dp"/>
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_edittext;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
 
public class MainActivity extends Activity {
 
	List<String> li;
	Spinner sp1,sp2;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        li=new ArrayList<String>();
        
        li.add("Data 1");
        li.add("Data 2");
        
        sp1=(Spinner) findViewById(R.id.spinner1);
        sp2=(Spinner) findViewById(R.id.spinner2);
        Button b=(Button) findViewById(R.id.button1);
        final EditText et=(EditText) findViewById(R.id.editText1);
        
        call();
        
        b.setOnClickListener(new View.OnClickListener() {
			
		public void onClick(View v) {
			// TODO Auto-generated method stub
				
			li.add(et.getText().toString());
			et.setText(null);
			call();
		}
	});
    }
 
    public void call() {
    	
	// TODO Auto-generated method stub
		
    	ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
    			android.R.layout.simple_dropdown_item_1line,li);
    	sp1.setAdapter(adp);
    	sp2.setAdapter(adp);
    	sp1.setSelection((li.size()-1));
    	
    	sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			
			// TODO Auto-generated method stub
				sp2.setSelection(arg2);
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});
    	
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_edittext"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_EditText</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output


Output


Output


Output


Output


Output









K. Spinner Selection defines Item for Another Spinner


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
 
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="50dp" />
 
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="15dp"
        android:layout_marginTop="50dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.spinner_selection_for_another;
 
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
	Spinner sp1,sp2;
	ArrayAdapter<String> adp1,adp2;
	List<String> l1,l2;
	int pos;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        l1=new ArrayList<String>();
        
        l1.add("A");
        l1.add("B");
        
        sp1= (Spinner) findViewById(R.id.spinner1);
        sp2= (Spinner) findViewById(R.id.spinner2);
        
        adp1=new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,l1);
        adp1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        sp1.setAdapter(adp1);
        
        sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
 
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
				
			pos = arg2;
			
			add();
		}
 
		private void add() {
			// TODO Auto-generated method stub
		        
	        switch(pos)
	        {
	        case 0:
	        	l2= new ArrayList<String>();		        	
	        	l2.add("A 1");
	        	l2.add("A 2");
	        	
	        	adp2=new ArrayAdapter<String>(MainActivity.this,
	        			android.R.layout.simple_dropdown_item_1line,l2);
	        	sp2.setAdapter(adp2);
	        	
	        	select();
	        	
	        	break;
	        	
	        case 1:
	        	l2= new ArrayList<String>();		        	
	        	l2.add("B 1");
	        	l2.add("B 2");
	        	
	        	adp2=new ArrayAdapter<String>(MainActivity.this,
	        			android.R.layout.simple_dropdown_item_1line,l2);
	        	sp2.setAdapter(adp2);
	        	
	        	select();
	        	
	        	break;
	        }
	        
		}
 
		private void select() {
			// TODO Auto-generated method stub
				
			sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
 
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub

				        Toast.makeText(getBaseContext(), l2.get(arg2),
						Toast.LENGTH_SHORT).show();
				}
 
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
						
				}
			});
		}
 
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
				
		}
	});        
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.spinner_selection_for_another"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">Spinner_Selection_for_Another</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output


Output









SHARE THIS PAGE



product 2

product 3

product 4

Feedbacks : balaji.scz@gmail.com