I have to develop an android view such that i have 2 spinner controls in it, one for state and the second for cities.
My question is, how can I populate the city spi
Example:
Spinner city=(Spinner)findViewById(R.id.citySpinner);
Spinner state=(Spinner)findViewById(R.id.stateSpinner);
final ArrayList state_options=new ArrayList();
final ArrayList city_options=new ArrayList();
state_options.add("state_1");
state_options.add("state_2");
state_options.add("state_3");
// Here you can also get a cursor and add Strings as options to state_options instead of what i have done
city_options.add("city_1_state_1");
city_options.add("city_2_state_1");
city_options.add("city_3_state_1");
// Here you can also get a cursor and add Strings as options to city_options instead of what i have done
ArrayAdapter cityAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item,city_options);
city.setAdapter(cityAdapter);
ArrayAdapter stateAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item,state_options);
state.setAdapter(stateAdapter);
state.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> arg0, View view,
int position, long id) {
String stateName=state_options.get(position).toString();
resetCity(stateName);
}
@Override
public void onNothingSelected(AdapterView> arg0) {
}
});
Now,
public void resetCity(String stateName)
{
city_options.removeAll(city_options);//i haven't checked this.
if(stateName.eqauls("state_1"))
{
city_option.add("city_1_state_1");
city_options.add("city_2_state_1");
city_options.add("city_3_state_1");
//you can also get a cursor and add Strings as options to city_options instead of what i have done
}
else if(stateName.eqauls("state_2"))
{
city_option.add("city_1_state_2");
city_options.add("city_2_state_2");
city_options.add("city_3_state_2");
// you can also get a cursor and add Strings as options to city_options instead of what i have done
}
else
{
city_option.add("city_1_state_3");
city_options.add("city_2_state_3");
city_options.add("city_3_state_3");
//you can also get a cursor and add Strings as options to city_options instead of what i have done
}
ArrayAdapter cityAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item,city_options);
city.setAdapter(cityAdapter);
}
This is the simplest example.You can set your city_options
and state_options
from your database.and then you can use it for populating accoring spinners.