Android - Dynamically Adding values to Spinners - android

I am new to Android Development so the query may seem novice.
I was trying to make an app where there are a couple of spinners and after the user selects one spinner the other spinner gets filled up with the data based on the selection in spinner1.
ie. First user selects Country. Based on country the spinner 2 gets filled up with states and based on the state the spinner 3 gets filled up with cities.
I have created all the countries as a string arrays in strings.xml like -
<string-array name="Country">
<item >USA</item> etc...
Similarly states have been created in the string.xml as - (Each Country is a separate entry with a naming convention as (country name)_(States)
<string-array name="USA_state">
<item >New York</item> etc...
Now I want the second spinner to populate based in country selection. Hence the formula used by me is to the get the second spinner is -
String getstate = country[index]+"_"+"state";
state=getResources()
.getStringArray(getResources().
getIdentifier(getstate,null,getPackageName()));
When I run this app the Manactivity just shows a blank screen and I donot get any Debug info and get an error "the jar file android.jar has no source attached".
Please help. The complete mainActivity is given below -
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.view.View;
public class MainActivity extends Activity {
String[] country;
String[] state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
country = getResources().getStringArray(R.array.country);
Spinner country_spinner =(Spinner) findViewById(R.id.country);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+"country", Toast.LENGTH_SHORT).show();
Fill (index);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
protected void Fill(int index) {
// TODO Auto-generated method stub
//Field resField=R.array.getField(country[index]);
//int getstate = resField.getInt(null);
String getstate = country[index]+"_"+"state";
state=getResources().getStringArray(getResources().getIdentifier(getstate,null,getPackageName()));
Spinner state_spinner = (Spinner) findViewById(R.id.state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, state);
state_spinner.setAdapter(adapter);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index2 = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),"You Have Selected "+state[index2] + " statet",Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

I was able to solve the problem. The final code is given below. This is a nested approach so if there are 3 spinners (like city after state) do we again nest the code for that spinner? Is there any simpler method?
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+" County", Toast.LENGTH_SHORT).show();
final CharSequence[] state_array = state.getTextArray(index);
final Spinner state_spinner =(Spinner) findViewById(R.id.state);
ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(MainActivity.this, android.R.layout.simple_spinner_item, state_array);
state_spinner.setAdapter(adapter1);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
final int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+state_array[index]+" State", Toast.LENGTH_SHORT).show();
});
}
public void onNothingSelected(AdapterView<?> arg0) {
state_spinner.setAdapter(null);
}
});

Related

Simple list item multiple choice not selecting items

I've created an array list and display it in a list view with simple list item multiple choice but i cannot check or tick the items on the list, when i click on the items nothing happens. Please check my code below and tell me what i am doing wrong.
package com.example.arrays;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
public class MainActivity extends Activity {
ListView showList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView show = (TextView)findViewById(R.id.txtShow);
final Random generate = new Random();
showList = (ListView)findViewById(R.id.listView1);
final String[] myAttraction = new String[4];
myAttraction[0]= "Walter Sisulu National Botanical Garden ";
myAttraction[1]= "Coca-Cola Dome";
myAttraction[2]= "Promusica Theatre";
myAttraction[3]= "Unisa Science Campus";
Button arrays = (Button)findViewById(R.id.button1);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
}
});
showList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Add a OnItemClickListener like this to check/uncheck the CheckedTextView when user click on an item
showList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// change the checkbox state
CheckedTextView checkedTextView = ((CheckedTextView)view);
checkedTextView.setChecked(!checkedTextView.isChecked());
}
});
change your code as following....
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
}
});
showList.setOnItemClickListener(new OnItemClickListener() {
public boolean onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
Set choiceMode property of your list to multipleChoice. I'm implementing multiple choice list in such a way in my applications, and it surely works.
Change this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
To this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
showList.setAdapter(adapter);
Just Add this line if you have a ListView and have selected simple_list_item_multiple_choice and you are unable to interact with the checkbox.
YourListViewName.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

How to get value from spinner in android ?

How to get values from drop down menu and use them in body of new message to be send.
Following is my code,
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
String phoneNo = editPhoneNum.getText().toString();
String sms = editSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,Toast.LENGTH_LONG).show();
}
}
try this
ArrayList<String> list = new ArrayList<String>(); //make this as field atribute
list.add("A");
list.add("B");
list.add("C");
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
list.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Declare your String label and String phoneNo variables globally and then pass it in your message body.
Append your spinner item in your sms string.
Supposing your class code
public class MainActivity extends Activity {
private String phoneNo,sms,label;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.............................
phoneNo = editPhoneNum.getText().toString();
sms = editSMS.getText().toString() + label;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
String label = parent.getItemAtPosition(position).getvalue();
getvalue().. according to location ur going getting only position. you have to get value yes use what value u want to get insted of getvalue() function name
Hi please have a look how we can do this i am sending example to you.
please look here
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
the full example is shown here as follows.
AndroidSpinnerExampleActivity.java
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
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 AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Text Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"
/>
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"
/>
</LinearLayout>

AutoCompleteTextView OnItemClick position is always "0"

the adapter works fine, but i don't understand why the position in OnItemClick is always "0"
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
int pos=position;
}
});
Don't ask me why, but the argument position in method OnItemClickListener.onItemClick holds the index relative to the AutoCompleteTextView's dropdown list, not the position in your adapter array (in your case regions)!
So, to find the item's real position you must get the string selected in the dropdown and find its index in the adapter array:
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getItemAtPosition(position);
int pos = Arrays.asList(regions).indexOf(selected);
}
});
I had the same issue: I couldn't manage to get the position, but I've figured out how to retrieve the whole object selected by the user (if any), having an ID field, which in my case is all I need.
The trick is not to use an ArrayAdapter<String> for the suggested items, but an ArrayAdapter<MyObject>, where MyObject overrides the toString() method.
For instance:
public class Country extends Object {
public int id;
public Country(int id) {
this.id = id;
}
#NonNull
#Override
public String toString() {
switch (id) {
case 0:
return "Albania";
case 1:
return "Romania";
case 2:
return "Ucraina";
case 3:
return "Russia";
default:
return "Unknwon";
}
}
}
...
private AutoCompleteTextView mNationAtv;
private Button mTestBtn;
private final Country[] COUNTRIES = {
new Country(0),
new Country(1),
new Country(2),
new Country(3)
};
...
// use object array for adapter
ArrayAdapter<Country> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
mNationAtv.setAdapter(adapter);
mTestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayAdapter<Country> ada = (ArrayAdapter<Country>) mNationAtv.getAdapter();
int nItems = ada.getCount();
// default Country unknown
Country selItem = new Country(5);
if (nItems > 0) {
selItem = (Country) ada.getItem(0);
}
Log.d(TAG,
"onClick(): nItems=" + nItems + ", selItem.name=" + selItem.toString()
+ ", selItem.id=" + selItem.id);
}
});
...
Logs:
when the AutocompleteTextView value matches an item in the dropdown:
onClick(): nItems=1, selItem.name=Ucraina, selItem.id=2
when the value is blank:
onClick(): nItems=4, selItem.name=Albania, selItem.id=0
when the value isn't blank but doesn't match any item in the dropdown:
onClick(): nItems=0, selItem.name=Unknown, selItem.id=5
You might want to fetch this value in the OnItemClickListener()::onItemClick() method, invoked avery time the user clicks an item in the dropdown, or outside of it, i.e. for validation.
I put this in a simple example and it works correctly for me. See below:
package com.example.autocompletetv;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
public class AutoCompleteActivity extends ListActivity {
public static final String TAG = AutoCompleteActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete);
String[] regions = {"One", "Two", "Three", "Four", "Five"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
this.setListAdapter(adapter);
this.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "postion was " + position);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_complete, menu);
return true;
}
}
When I click I get:
12-09 19:13:30.617: I/AutoCompleteActivity(1883): postion was 2
12-09 19:13:31.997: I/AutoCompleteActivity(1883): postion was 3
12-09 19:13:34.687: I/AutoCompleteActivity(1883): postion was 4
12-09 19:13:37.028: I/AutoCompleteActivity(1883): postion was 0

Second Spinner not receiving the proper info based on the first Spinner's selection

I know there are about a million topics on this already, but hear me out.
The title says it all, when i select an item in spinner 1, spinner 2 gets a specific list of choices to pick from (which will then be used to show info). It's essentially a small contacts book.
*UPDATE**
All fixed and working, and an EXTRA special thank you to user FishTruck for helping out(i.e making it work!)
package com.your.package.name;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class Contact extends Activity{
public Spinner spinner1, spinner2;
public Button btnSubmit;//not needed yet
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.contact);
findViews();
addItemsOnSpinner1();
addItemsOnSpinner2(0);
}
private void findViews(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
}
private void addItemsOnSpinner1() {
List<String> list = new ArrayList<String>();
list.add("Please Select");
list.add("Choice 1");
list.add("choice 2");
ArrayAdapter<String> name = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
name.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(name);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
if(arg2>0)
addItemsOnSpinner2(arg2);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
addItemsOnSpinner2(0);
}}
);
}
private void addItemsOnSpinner2(int selectedIndex) {
int positionTop = selectedIndex;
if(positionTop==0){
List<String> list = new ArrayList<String>();
list.add("Please Select");
ArrayAdapter<String> name0 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
name0.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(name0);
}else if(positionTop==1){
List<String> list1 = new ArrayList<String>();
list1.add("Please Select");
list1.add("item 1");
list1.add("item 2");
ArrayAdapter<String> name1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list1);
name1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(name1);
}else if(positionTop==2){
List<String> list2 = new ArrayList<String>();
list2.add("Please Select");
list2.add("item 3");
list2.add("item 4");
ArrayAdapter<String> name2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list2);
name2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(name2);
}
}
}
Hope this helps!
You need to call the addItemsOnSpinner2() function when the first spinner item has got selected.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
addItemsOnSpinner2();}
yes as the gentlemen before me said.
In order for the second spinner to get the correct index to set the list,
you need to populate it after the first spinner is clicked.
/* wrong answer deleted */
if this is my code i would change addItemsOnSpinner2() into:
private void addItemsOnSpinner2(int selectedIndex){
int positionTop = selectedIndex;
//rest is the same
/* ... */
}
and again insert these into addItemsOnSpinner1():
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
if(arg2>0)
addItemsOnSpinner2(arg2);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
addItemsOnSpinner2(0);
}}
);
that is just how i would do it
i think many ways works here though
edit2:oh and edit the addItemsOnSpinner2() in onCreate() into addItemsOnSpinner2(0)
edit3:you need to call addItemsOnSpinner2() in onCreate(), otherwise your spinner is empty!
edit4:sorry guys, i made a huge mistake into thinking onItemClickListener could be applied here, shame on me :((
btw, if you want to keep the index (under situation like change of screen orientation or back to foreground ) , it needs more complicated work
but here is a much simpler method:
1.set a global static variable: int selectedIndex;
2.in onCreate, set selectedIndex to 0 if savedInstanceState is null
3.in onCreate, after savedInstanceState is nullcheckd, call addItemsOnSpinner2(selectedIndex)
4.in spinner1's listener, set selectedIndex to selected index.
not guarranteed to work on every machine though:(
you are setting both spinner at the beginning of the code ( in onCreate). You should populate the second spinner after the spinner1 data is changed

how to use spinner

I am very new to android. I want to use 2 spinners in my application, one shows the countries list, when any country is selected the other spinner should show the list of cities of that country. when city is selected some action is performed. plz help me with some sample code. thanks in anticipation
Here is something what we can use to add options to spinner2 w.r.t to spinner 1.
public class Activity extends Activity implements View.OnClickListener
{
private Spinner spinner0, spinner1, spinner2, spinner3;
private Button submit, cancel;
private String country[], state[], city[], area[];
Australia aus = new Australia();
Object object;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner0 = (Spinner)findViewById(R.id.spinnerCountry);
spinner1 = (Spinner)findViewById(R.id.spinnerQ1);
spinner2 = (Spinner)findViewById(R.id.spinnerQ2);
spinner3 = (Spinner)findViewById(R.id.spinnerQ3);
submit = (Button)findViewById(R.id.btnSubmit);
cancel = (Button)findViewById(R.id.btnCancel);
submit.setOnClickListener(this);
cancel.setOnClickListener(this);
country = new String[] {"Select Country", "Australia", "USA", "UK", "New Zealand", "EU", "Europe", "China", "Hong Kong",
"India", "Malaysia", "Canada", "International", "Asia", "Africa"};
ArrayAdapter<String> adapter0 = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, country);
adapter0.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner0.setAdapter(adapter0);
Log.i("AAA","spinner0");
spinner0.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View view1, int pos, long id)
{
Log.i("AAA","OnItemSelected");
int loc;
loc = pos;
switch (loc)
{
case 1:
state = aus.getState();
object = aus;
Log.i("AAA","ArrayAdapter1");
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, state);
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner1.setAdapter(adapter1); Log.i("AAA","spinner1");
break;
default:
Log.i("AAA","default 0");
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg1)
{
Log.i("AAA","Nothing S0");
}
});
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View view1, int pos, long id)
{
Log.i("AAA","OnItemSelected S1");
int loc = pos;
switch(loc)
{
case 1:
Log.i("AAA","Australia");
if(object.equals(aus))
{
city = aus.getType(loc);
}
else
{
break;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, city);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter); Log.i("AAA","spinner2");
break;
default:
Log.i("AAA", "default 1");
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
Log.i("AAA","Nothing S1");
}
});
spinner2.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long id)
{
int loc = pos;
switch (loc)
{
case 1:
if(object.equals(aus))
{
area = aus.getTitle(loc);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, area);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner3.setAdapter(adapter); Log.i("","spinner3");
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}// on-create
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btnSubmit:
break;
case R.id.btnCancel:
finish();
break;
default:
break;
}
}
}
If you find this useful, then do give it up vote, so that others can find a good answer easily.
For each Country, you have to create a class for it, to just add State, City & Area. So that it doesn't become a mesh at a single at single page.
Have fun.
Regards,
Haps.
Here is a sample code which depicts the usage of spinner and action performed when spinner item is selected
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends Activity {
Spinner spin;
String spin_val;
String[] gender = { "Male", "Female" };//array of strings used to populate the spinner
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//setting layout
spin = (Spinner) findViewById(R.id.spinner_id);//fetching view's id
//Register a callback to be invoked when an item in this AdapterView has been selected
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
spin_val = gender[position];//saving the value selected
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//setting array adaptors to spinners
//ArrayAdapter is a BaseAdapter that is backed by an array of arbitrary objects
ArrayAdapter<String> spin_adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, gender);
// setting adapteers to spinners
spin.setAdapter(spin_adapter);
}
}
To add a list of values to the spinner, you then need to specify a SpinnerAdapter in your Activity, which extends Adapter class.. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.You can also download & refer to the complete spinner_demo example project for better understanding.
Check the following examples :
https://developer.android.com/guide/tutorials/views/hello-spinner.html
http://www.designerandroid.com/?cat=4

Categories

Resources