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
Related
I have 2 spinners in an activity.
Based on the selection of one item in spinner1, relevant data should be loaded in spinner2. Consider spinner1 has data related to country and spinner2 has data related to state.
I should be able to get this done once the activity is created and if the user changes the selection in spinner1.
But I am stuck with populating the spinner2 data based on the saved value of spinner1.
I am calling spinner1.setSelection(indexSaved) but since I am only loading spinner2 in the onItemSelectedOf of spinner1, setSelection of spinner1 is not firing the onItemSelected.
Please let me know how I can achieve this.
I have done same thing in my project without any problem:
Below is code may be it help you:
On Create Method filled state list:
//initialize spinners
spinnerStateList = (Spinner) findViewById(R.id.spinnerStateList);
spinnerDistrictsList = (Spinner) findViewById(R.id.spinnerDistrictsList);
fillStateList();
public void fillStateList()
{
states = manage_states.fetchAllStates(getApplicationContext());
//add new element for select name
states.add(0,new RowItem("-1", "Select State"));
String[] spinnerArray = new String[states.size()];
for(int i= 0;i<states.size();i++)
{
spinnerArray[i] = states.get(i).getName();
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,spinnerArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStateList.setAdapter(dataAdapter);
spinnerStateList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String selectedStateID = states.get(position).getId();
fillDistrictsSelectionChangeState(selectedStateID);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void fillDistrictsSelectionChangeState(String selectedStateID)
{
if(selectedStateID.equalsIgnoreCase("-1"))
{
linearLayoutDistrictsList.setVisibility(LinearLayout.GONE);
linearLayoutBlocksList.setVisibility(LinearLayout.GONE);
linearLayoutPHCList.setVisibility(LinearLayout.GONE);
linearLayoutSHCList.setVisibility(LinearLayout.GONE);
}
else
{
linearLayoutDistrictsList.setVisibility(LinearLayout.VISIBLE);
districts = manage_districts.fetchAllDistrictsByStateId(getApplicationContext(), selectedStateID);
//add new element for select name
districts.add(0,new RowItem("-1", "Select District"));
String[] spinnerArray = new String[districts.size()];
for(int i= 0;i<districts.size();i++)
{
spinnerArray[i] = districts.get(i).getName();
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,spinnerArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDistrictsList.setAdapter(dataAdapter);
spinnerDistrictsList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String selectedDistrictID = districts.get(position).getId();
fillBlocksSelectionChangeDistrict(selectedDistrictID);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
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
I am trying to get a screen transition when i select a value from the spinner. My spinner has just 2 values. The 1st one is selected by default. What I want is that when i click on the 2nd value in my spinner, it should take me to the new screen.
Please Help!
Thanks in advance!
Use onItemSelectedListener of your Spinner. Here is a Demo,
public class AndroidSpinner extends Activity implements OnItemSelectedListener {
TextView selection;
Spinner spin;
String[] items = { "bangladesh", "bangla", "bd", "australia", "japan",
"china", "indiaA", "indiaC" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Spinner spin = new Spinner(this);
setContentView(spin);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
spin.setAdapter(aa);
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// Do your Stuff Here
Intent intent = new Intent(MyActivity.this, NextActivity.class);
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
selection.setText("");
}
}
Assuming that you know how to set up the spinner adapter and everything, simply add the code to go to the next screen when the other item is selected on the spinner.
public void onItemSelected(AdapterView<?> parent, View v, int position, long id)
{
if(position ==0)
//do nothing (assuming that you would want to stay in the same screen)
else if (position ==1)
{
//go to the next screen, probably by using an INTENT to the next activity or using setContentView(theLayoutXmlFile)
}
}
Use below code for open new activity or new screen onitemselected event of spinner.
public class SpinnerExample extends Activity implements OnItemSelectedListener {
String[] items = { "Dipak", "Aadi", "Bharat", "Pratik", "Usha", "Jayesh", "Deep", "Imran" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner mSpn1 = (Spinner) findViewById(R.id.mSpn1);
mSpn1.setOnItemSelectedListener(this);
ArrayAdapter<String> adpt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
mSpn1.setAdapter(adpt);
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// Do your Stuff Here
// For Open New Activity
Intent mInNewAccount = new Intent(MainActivity.this, SecondActivity.class);
startActivity(mInNewAccount);
finish();
// For Open New Screen
setContentView(R.layout.second_screen);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
The items of the first one are defined in xml (<string-array>) but the second one should present different items arrays of strings according what is selected on the first...
The possible array of strings for the seconds are fetch from a web service using an AsyncTask (This part is working). In my onPostExecute(Void result) I have this:
private class GetInfoTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(StateTabActivity.this);
//...
#Override
protected void onPostExecute(Void result) {
Log.d("StateTabActivity","onPostExecute");
sectorsArray = getSectorsName(); // sectorsArray is an array of strings
roomsArray = getRoomsName(); // roomsArray is an array of strings
subcategorySpinnerAdapter = new ArrayAdapter<String>(StateTabActivity.this, R.layout.my_spinner,sectorsArray);
subcategorySpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
subCategorySpinner.setAdapter(subcategorySpinnerAdapter);
dialog.dismiss();
}
}
On the onCreate() of my activity I have:
Spinner categorySpinner = (Spinner) findViewById(R.id.statetab_category_spinner);
ArrayAdapter<String> categorySpinnerAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner,getResources().getStringArray(R.array.array_category));
categorySpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categorySpinner.setAdapter(categorySpinnerAdapter);
subCategorySpinner = (Spinner) findViewById(R.id.statetab_subcategory_spinner);
categorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Log.d("StateTabActivity","in onitemselected");
switch (arg2) {
case 0:
//I want to set here the items of sectorsArray to be displayed on the second spinner (subCategorySpinner)
break;
case 1:
//I want to set here the items of roomsArray to be displayed on the second spinner (subCategorySpinner)
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
So my question is: What should I do to bind the right array to the second spinner, according what is selected on the first one?
This is my code to get district list as per selected state.
final Spinner state = (Spinner)_activity.findViewById(R.id.state);
final Spinner district= (Spinner) _activity.findViewById(R.id.district);
_activity.findViewById(R.id.name_of_city);
state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapter, View v, int i, long lng) {
if(i == 0){
districtAdapter =new ArrayAdapter<CharSequence>( _activity , android.R.layout.simple_spinner_item, **DistrictList**.AndraPradesh);
//DistricList is another class.its code given below
districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
district.setAdapter(districtAdapter);
if(_viewState == SAVED_VIEW){
district.setSelection(getArraySpinner(DistrictList.AndraPradesh,_initialValues.getAsString("District")),true);
}
}
In DistricList class,
public class DistrictList {
public static final String[] AndraPradesh = new String[] {"Adilabad",
"Anantapur",
"Chittoor",
"East Godavari",
"Guntur",
"Hyderabad",
"Karimnagar",
"Khammam"};
}
}
I'm begginer in android. I'm working on a project. But i get very difficult to do two spinners related to each others. Actually one spinner for the country and another for the city. Instead of the country that is chosen the second spinner will show the cities.
I'v used "OnItemSelectedListener" but the " ArrayAdapter.createFromResource " can't be used inside OnItemSelectedListener.
I've tried a lot of other ways but still none of them working.
Can anybody help me Please???
(P.S. I have read and tried the other posts about this topic but it still doesn't work )
This is the code:
spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
int spinnerId = spinner.getSelectedItemPosition();
if (spinnerId==0){
adaptert = ArrayAdapter.createFromResource(
this, R.array.tirana, android.R.layout.simple_spinner_item);
adaptert.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
else if (spinnerId==1) {
adaptert = ArrayAdapter.createFromResource(
this, R.array.durres, android.R.layout.simple_spinner_item);
adaptert.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
spinnert.setAdapter(adaptert);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
public class AdapterViewImplementation extends Activity implements OnItemSelectedListener{
Spinner sp1; // One Spinner
Spinner sp2; // Another Spinner
ArrayAdapter stateAdapter; // Adapter for state
ArrayAdapter cityAdapter; // Adapter for city
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sp1 = (Spinner)findViewById(R.id.Spinner01);
sp2 = (Spinner)findViewById(R.id.Spinner02);
stateAdapter = ArrayAdapter.createFromResource(AdapterViewImplementation.this,
R.array.state, android.R.layout.simple_spinner_item);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(stateAdapter);
sp1.setOnItemSelectedListener(AdapterViewImplementation.this);
cityAdapter = ArrayAdapter.createFromResource(AdapterViewImplementation.this,
R.array.city, android.R.layout.simple_spinner_item);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(cityAdapter);
sp2.setOnItemSelectedListener(AdapterViewImplementation.this);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(arg0 == sp1){
sp2.setSelection(arg2);
}else{
sp1.setSelection(arg2);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}