I've got numbers from 1 to 12 in spinner1, and another spinner2 that I'd like to be controlled by what the user picked in the former.
Whenever user selects a number between from 1 to 6 in spinner1, spinner2 should show numbers from 1 to 31.
Whenever user selects a number between from 7 to 12 in spinner1, spinner2 should show numbers from 1 to 30.
I've managed to come up with this code, but it does not seem to work as above. Could help me in finding what's wrong?
package com.example.spinners;
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.Spinner;
public class MainActivity extends Activity {
Spinner sp1, sp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp1 = (Spinner) findViewById(R.id.SP1);
sp2 = (Spinner) findViewById(R.id.SP2);
List<String> list = new ArrayList<String>();
list.add("1"); list.add("2"); list.add("3"); list.add("4");
list.add("5"); list.add("6"); list.add("7"); list.add("8");
list.add("9"); list.add("10"); list.add("11"); list.add("12");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(dataAdapter);
//
sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// userSelectedIndex = position;
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
//
if (sp1.getSelectedItem().equals("1") || sp1.getSelectedItem().equals("2")
|| sp1.getSelectedItem().equals("3") || sp1.getSelectedItem().equals("4")
|| sp1.getSelectedItem().equals("5") || sp1.getSelectedItem().equals("6")) {
//
List<String> list2 = new ArrayList<String>();
list2.add("1"); list2.add("2"); list2.add("3"); list2.add("4"); list2.add("5");
list2.add("6"); list2.add("7"); list2.add("8"); list2.add("9"); list2.add("10");
list2.add("11"); list2.add("12"); list2.add("13"); list2.add("14");
list2.add("15"); list2.add("16"); list2.add("17"); list2.add("18");
list2.add("19"); list2.add("20"); list2.add("21"); list2.add("22");
list2.add("23"); list2.add("24"); list2.add("25"); list2.add("26");
list2.add("27"); list2.add("28"); list2.add("29"); list2.add("30");
list2.add("31");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(dataAdapter2);
} else if(sp1.getSelectedItem().equals("7") || sp1.getSelectedItem().equals("8") || sp1.getSelectedItem().equals("9") || sp1.getSelectedItem().equals("10") || sp1.getSelectedItem().equals("11") || sp1.getSelectedItem().equals("12")) {
/////////////////////////////////////////////////////////
//
List<String> list2 = new ArrayList<String>();
list2.add("1"); list2.add("2"); list2.add("3"); list2.add("4"); list2.add("5");
list2.add("6"); list2.add("7"); list2.add("8"); list2.add("9"); list2.add("10");
list2.add("11"); list2.add("12"); list2.add("13"); list2.add("14");
list2.add("15"); list2.add("16"); list2.add("17"); list2.add("18");
list2.add("19"); list2.add("20"); list2.add("21"); list2.add("22");
list2.add("23"); list2.add("24"); list2.add("25"); list2.add("26");
list2.add("27"); list2.add("28"); list2.add("29"); list2.add("30");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(dataAdapter2);
}
//
}
}
The problem in your code is, that you are checking the selected value only once, before the window has even opened. You need to check it every time a user changes the value. So you need that logic in your onItemSelectedListener. Here the revised code, with a few improvements (untested, but it should work).
public class MainActivity extends Activity {
private Spinner sp1, sp2;
private List<Integer> firstList = new ArrayList<Integer>();
private List<Integer> secondList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp1 = (Spinner) findViewById(R.id.SP1);
sp2 = (Spinner) findViewById(R.id.SP2);
for (int i = 1; i <= 12; i++) {
firstList.add(i);
}
ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, firstList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(dataAdapter);
sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int currentValue = firstList.get(position);
if(currentValue <= 6){
for (int i = 1; i <= 30; i++) {
secondList.add(i);
}
} else {
for (int i = 1; i <= 31; i++) {
secondList.add(i);
}
}
ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(MainActivity.this, android.R.layout.simple_spinner_item, secondList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(dataAdapter);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Related
i want to change the spinner-array of my Spinner2 by selecting something on my Spinner1.
It means if i change the selecteted item of spinner1 to position 2,3 etc. the listener has to change the whole items of my spinner2. (array in Strings.xml)
I tried to set it to another adapter but doesn't work...
Can anyone help me? thx
Here's my code:
public class DamenBH extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner1;
Spinner spinner2;
ArrayAdapter<CharSequence> adapter1;
ArrayAdapter<CharSequence> adapter65, adapter70, adapter75;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_damen_b_h);
spinner1 = findViewById(R.id.spinner1);
adapter1 = ArrayAdapter.createFromResource(this, R.array.beispiel1, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner2 = findViewById(R.id.spinner2);
spinner2.setOnItemSelectedListener(this);
adapter65 = ArrayAdapter.createFromResource(this, R.array.beispiel2, android.R.layout.simple_spinner_item);
adapter65.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner2.setAdapter(adapter65);
adapter70 = ArrayAdapter.createFromResource(this, R.array.beispiel3, android.R.layout.simple_spinner_item);
adapter70.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
adapter75 = ArrayAdapter.createFromResource(this, R.array.beispiel4, android.R.layout.simple_spinner_item);
adapter75.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner1.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
spinner2.setAdapter(adapter65);
break;
case 1:
spinner2.setAdapter(adapter70);
break;
case 2:
spinner2.setAdapter(adapter75);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I came up with this and it seems to work fine for me.
package com.example.energydrinkapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.lang.reflect.Array;
public class EnterInfoActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner manufacturer;
ArrayAdapter<CharSequence> manufacturerAdapter;
Spinner flavor;
ArrayAdapter<CharSequence> flavorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_info);
manufacturer = (Spinner) findViewById(R.id.spinner_manufacturer);
manufacturer.setOnItemSelectedListener(this);
manufacturerAdapter = ArrayAdapter.createFromResource(this, R.array.manufacturer_array, android.R.layout.simple_spinner_item);
manufacturerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
manufacturer.setAdapter(manufacturerAdapter);;
}
public void flavorArraySet(int flavors){
flavor = (Spinner) findViewById(R.id.spinner_flavor);
flavorAdapter = ArrayAdapter.createFromResource(this, flavors, android.R.layout.simple_spinner_item);
flavorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
flavor.setAdapter(flavorAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
Log.e("array","none");
}
else if (position == 1){
Log.e("array", "monster");
flavorArraySet(R.array.monster_array);
}
else if (position == 2){
Log.e("array", "red bull");
flavorArraySet(R.array.redbull_array);
}
else if (position == 3){
Log.e("array", "reign");
flavorArraySet(R.array.reign_array);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
I'm trying to populate value of the next spinner from the previous spinner. In this case, what I did yet is generating all values inside the spinner means, no matter which value I select in the previous spinner it is always showing all values in the next spinner. I'm using five spinners that needs to populate values according to the previous one. Here I'm using a library for the spinner. The library is as follows.
'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
Here I'm sharing my whole code/class for your consideration. There is no error and I get all values in respective spinner but I want to get values according to the previous one. here is my code.
import androidx.appcompat.app.AppCompatActivity;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;
public class Catchment extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public ArrayAdapter<String> regionAdapter;
public ArrayAdapter<String> districtAdapter;
public ArrayAdapter<String> upzAdapter;
public ArrayAdapter<String> unionAdapter;
public ArrayAdapter<String> villageAdapter;
public String[] Region = {"1", "2",
};
public String[] District = {"1","2","3","4","5","6","7","8",};
public String[] Upz = {"1","2"...."23";
public String[] Union = {"1","2"...."25"..."50"...."115"};
public String[] Village = { "1","2"...."25"..."50"...."150"...."500"...."947" };
Button catchment_code;
SearchableSpinner spinner_region, spinner_district, spinner_upz, spinner_union, spinner_village;
String[] region_code;
String[] district_code;
String[] upz_code;
String[] union_code;
String[] vill_code;
int positions;
String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catchment);
spinner_region = (SearchableSpinner) findViewById(R.id.region);
spinner_district = (SearchableSpinner) findViewById(R.id.district);
spinner_upz = (SearchableSpinner) findViewById(R.id.upz);
spinner_union = (SearchableSpinner) findViewById(R.id.union);
spinner_village = (SearchableSpinner) findViewById(R.id.village);
catchment_code = findViewById(R.id.catchment_code);
// Set spninner adapter
regionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Region);
districtAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, District);
upzAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Upz);
unionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Union);
villageAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Village);
//Set dropdown to the spinner
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
upzAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
unionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
villageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//assign to spinner
spinner_region.setAdapter(regionAdapter);
spinner_district.setAdapter(districtAdapter);
spinner_upz.setAdapter(upzAdapter);
spinner_union.setAdapter(unionAdapter);
spinner_village.setAdapter(villageAdapter);
spinner_region.setOnItemSelectedListener(this);
spinner_district.setOnItemSelectedListener(this);
spinner_upz.setOnItemSelectedListener(this);
spinner_union.setOnItemSelectedListener(this);
spinner_village.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.region) {
positions = spinner_region.getSelectedItemPosition();
region_code = this.getResources().getStringArray(R.array.region_code);
//Toast.makeText(this, region_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.district) {
positions = spinner_district.getSelectedItemPosition();
district_code = this.getResources().getStringArray(R.array.district_code);
//Toast.makeText(this, district_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.upz) {
positions = spinner_upz.getSelectedItemPosition();
upz_code = this.getResources().getStringArray(R.array.upz_code);
//Toast.makeText(this, upz_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.village) {
positions = spinner_village.getSelectedItemPosition();
vill_code = this.getResources().getStringArray(R.array.village_code);
//Toast.makeText(this, vill_code[positions], Toast.LENGTH_LONG).show();
}
if (parent.getId() == R.id.union) {
positions = spinner_union.getSelectedItemPosition();
union_code = this.getResources().getStringArray(R.array.union_code);
//Toast.makeText(this, union_code[positions], Toast.LENGTH_SHORT).show();
}
if (!(vill_code == null || region_code == null || district_code == null || upz_code == null ||
union_code == null)) {
test = region_code[positions] +
district_code[positions] +
upz_code[positions] +
union_code[positions] + vill_code[positions];
Toast.makeText(this, test, Toast.LENGTH_SHORT).show();
}
catchment_code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Catchment.this, Participant_Details.class);
intent.putExtra("catment_code", test);
startActivity(intent);
}
});
//Toast.makeText(this, union_code[positions]+upz_code[positions], Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Catchment.this, SplashScreen.class);
Catchment.this.startActivity(intent);
Catchment.this.finish();}
}
So how can I get rid of this problem? I need help.
You are declaring all adapter at once in onCreate().
Instead declare just first adapter with values in onCreate() and declare other adapters with empty values.
#Override
protected void onCreate(Bundle savedInstanceState) {
--------;
// Set spninner adapter
regionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Region);
districtAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
upzAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
unionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
villageAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]());
------
spinner_region.setOnItemSelectedListener(this);
}
Now on itemSelectedListener, filter the desired values if needed and add the values to the next required adapter and notify the values along with adding listener to next spinner(adding listener is up to you, how you want to handle the things)
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.region) {
positions = spinner_region.getSelectedItemPosition();
String[] filteredDistrict = District.filter(Region[position]) // District.filter is not any predefined function, assuming some filter needed for selected Districts
districtAdapter.addValues(filteredDistrict);
districtAdapter.notifyDataSetChanged()
spinner_district.setOnItemSelectedListener(this);
}
}
Other than that filtering logic depends on your usecase.
I am new to android, I am trying to implement the cascading spinner. When I select the first spinner it should populate the second spinner choices based on the 1st spinner selection. I have almost done, but in second spinner I cannot select the value. When I select the value it is disappearing. Please help me in this.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class DummyMain extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public Spinner spinner1, spinner2;
public String[] spinner1Values = {"A", "B"}, valuesForA = {"1", "2"}, valuesForB = {"3", "4", "5", "1"};
public ArrayAdapter<String> adapterForSpinner1, adapterForSpinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
adapterForSpinner1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, spinner1Values);
adapterForSpinner1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapterForSpinner1);
spinner1.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
Toast.makeText(this, "Result "+spinner1.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
if (parent.getId() == R.id.spinner1) {
if (spinner1.getSelectedItem().toString().equals("A")) {
adapterForSpinner2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item,valuesForA);
adapterForSpinner2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapterForSpinner2);
spinner2.setOnItemSelectedListener(this);
} else {
adapterForSpinner2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item,valuesForB);
adapterForSpinner2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapterForSpinner2);
spinner2.setOnItemSelectedListener(this);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Found the issue, I have fixed it.
ArrayAdapter<String> adapterForSpinner2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, valuesForB);
I have changed the getApplicationConetxt() into this. It works :-)
ArrayAdapter<String> adapterForSpinner2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, valuesForB);
try adding this in your DummyMain
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
I have this code so far. The Model Spinner automatically populates according to what the user picks for the Manufacture. (For the code below I only have it set up for BMW). Is there any way for the third spinner (Color) to be populated based on the Manufacture and Model.
So if you select BMW on the first spinner and then you select M3 coupe for the second spinner the third spinner would show all the option in the M3_Color Array.
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.Spinner;
public class MainActivity extends Activity implements OnItemSelectedListener {
private String[] Manufacture { "Ford",
"BMW",
"Nissan",
"Toyota",
"Chevy",
};
private String[] BMW_Model = { "128i Coupe",
"M3 Coupe",
"M5 Sedan",
"640i Gran Coupe",
"335i Coupe",
};
private String[] M3_Color = { "Jerez Black Metallic",
"Melbourne Red Metallic",
"Mineral White Metallic",
"Le Mans Blue Metallic",
};
Spinner spinnerManufacture, spinnerModel, spinnerColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerManufacture = (Spinner) findViewById(R.id.manufacture_spinner);
ArrayAdapter<String> MaufactureAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,Manufacture);
MaufactureAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerManufacture.setAdapter(MaufactureAdapter);
spinnerManufacture.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
// TODO Auto-generated method stub
{
if(parent.getId() == R.id.maufacture_spinner && position == 1)
{
spinnerModel = (Spinner) findViewById(R.id.model_spinner);
ArrayAdapter<String> ModelAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, BMW_Model);
ModelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerModel.setAdapter(ModelAdapter);
if(parent.getId() == R.id.model_spinner)
{
String[] Color;
if(spinnerMaufacture.getSelectedItem().toString.equals("BMW"))
{
if(spinnerModel.getSelectedItem().toString.equals("M3 Coupe))
{
Color = M3_Color
}
}
spinnerColor = (Spinner) findViewById(R.id.color_spinner);
ArrayAdapter<String> ColorAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, M3_Color);
ColorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerColor.setAdapter(ColorAdapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
you need to move if(parent.getId() == R.id.model_spinner) outside if(parent.getId() == R.id.maufacture_spinner then makesure and call spinnerModel.setOnItemSelectedListener(this) onCreate, to do that you need to move spinnerModel = (Spinner) findViewById(R.id.model_spinner) into your on create, I'd recommend doing the same for all your views, that way you don't call findViewById every time you select a spinner item.
EDIT:
Spinner spinnerManufacture, spinnerModel, spinnerColor;
private ArrayAdapter<String> modelAdapter;
private ArrayAdapter<String> maufactureAdapter;
private ArrayAdapter<String> colorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinnerManufacture = (Spinner) findViewById(R.id.manufacture_spinner);
spinnerModel = (Spinner) findViewById(R.id.model_spinner);
spinnerColor = (Spinner) findViewById(R.id.color_spinner);
maufactureAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Manufacture);
modelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
colorAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
maufactureAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
modelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerColor.setAdapter(colorAdapter);
spinnerManufacture.setAdapter(maufactureAdapter);
spinnerModel.setAdapter(modelAdapter);
spinnerManufacture.setOnItemSelectedListener(this);
spinnerModel.setOnItemSelectedListener(this);
spinnerColor.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.maufacture_spinner) {
String[] model;
if (spinnerManufacture.getSelectedItem().toString().equals("BMW")){
model = BMW_Model;
} else {
model = new String[] {"not sure what model list to use"};
}
modelAdapter.clear();
modelAdapter.addAll(model);
}
if (parent.getId() == R.id.model_spinner) {
String[] Color;
if (spinnerModel.getSelectedItem().toString().equals("M3 Coupe")) {
Color = M3_Color;
} else if (spinnerModel.getSelectedItem().toString().equals("M5 Sedan")) {
Color = M5_Color;
} else {
Color = new String[] { "not sure what color list to use" };
}
colorAdapter.clear();
colorAdapter.addAll(Color);
}
}
this is what I recommend you try.
Just build the string based on what is selected like below. This sets the color list as M3_Color for BMW and M3 Coupe being selected, and M5_Color when BMW and M5 Sedan are selected. This would need to be done for all possible combinations.
if(parent.getId() == R.id.model_spinner)
{
String[] Color = new String[];
if(spinnerManufacture.getSelectedItem().toString().equals("BMW"))
{
if(spinnerModel.getSelectedItem().toString().equals("M3 Coupe"))
{
Color = M3_Color;
}
else if(spinnerModel.getSelectedItem().toString().equals("M5 Sedan"))
{
Color = M5_Color;
}
}
spinnerColor = (Spinner) findViewById(R.id.color_spinner);
ArrayAdapter<String> ColorAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, Color);
ColorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerColor.setAdapter(ColorAdapter);
}
I would like to develop an android app with three spinners.
These three spinners will contain the information about the cars, which are brands, models, and engines.
So, after the first spinner(brand) is chosen, the contents of the second spinner(model) should be added depend on the selected brand.
Next, the second spinner will be selected and then the third spinner(engine) will be added.
I have searched with keyword "Android Multi Spinners" and "Android listener for spinners" on google and stackoverflow for almost a week, but I still didn't find the solution.
Here are the links that I got the idea for my code
multiple spinner's simple doubts
Spinner listener not working
So, I have two versions of my source code, but both of them didn't work. (Edited: Working now)
For the first version
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 AddCarActivity extends Activity {
private Spinner spnBrand, spnModel, spnEngine;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_car);
addItemsOnSpnBrand();
}
public void addItemsOnSpnBrand() {
spnBrand = (Spinner) findViewById(R.id.spnBrand);
List<String> list = new ArrayList<String>();
//Get Brand Database and Add to List
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnBrand.setAdapter(dataAdapter);
addListenerOnSpnBrandItemSelection();
}
public void addListenerOnSpnBrandItemSelection() {
spnBrand = (Spinner) findViewById(R.id.spnBrand);
spnBrand.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
addItemOnSpnModel(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
});
}
public void addItemOnSpnModel(String inBrand) {
spnModel = (Spinner) findViewById(R.id.spnModel);
List<String> list = new ArrayList<String>();
//Get Model Database and Add to List
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnSeries.setAdapter(dataAdapter);
addListenerOnSpnModelItemSelection();
}
public void addListenerOnSpnModelItemSelection() {
spnModel = (Spinner) findViewById(R.id.spnModel);
spnModel.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
addItemOnSpnEngine(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView<?> parent) {
return;
}
});
}
public void addItemOnSpnEngine(String inModel) {
spnEngine = (Spinner) findViewById(R.id.spnEngine);
List<String> list = new ArrayList<String>();
//Get Engine Database and Add to List
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnEngine.setAdapter(dataAdapter);
}
}
Here is my Second version
public class AddCarActivity extends Activity implements OnItemSelectedListener {
private Spinner spnBrand, spnModel, spnEngine;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_car);
addItemsOnSpnBrand();
}
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3) {
int id = parent.getId();
switch (id)
{
case R.id.spnBrand:
addItemOnSpnModel(parent.getItemAtPosition(position).toString()); break;
case R.id.spnModel:
addItemOnSpnEngine(parent.getItemAtPosition(position).toString()); break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
return;
}
public void addItemsOnSpnBrand() {
spnBrand = (Spinner) findViewById(R.id.spnBrand);
List<String> list = new ArrayList<String>();
//Get Brand Database and Add to List
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnBrand.setAdapter(dataAdapter);
spnBrand.setOnItemSelectedListener(this);
}
public void addItemOnSpnModel(String inBrand) {
spnModel = (Spinner) findViewById(R.id.spnModel);
List<String> list = new ArrayList<String>();
//Get Model Database and Add to List
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnModel.setAdapter(dataAdapter);
spnModel.setOnItemSelectedListener(this);
}
public void addItemOnSpnEngine(String inModel) {
spnEngine = (Spinner) findViewById(R.id.spnEngine);
List<String> list = new ArrayList<String>();
//Get Engine Database and Add to List
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnEngine.setAdapter(dataAdapter);
}
}
Thank you everyone that have tried to help me. I just found the problem when retest the codes for answering Hip Hip Array. I use the wrong variable in addListenerOnSpnModelItemSelection(). I mistaken to use spnBrand instead of spnModel. Now, these two versions are worked, so I corrected them and hope that they will help the others that try to use the multi-spinners in android.
Bit long winded but give it a try
Public class HomePage extends Activity implements OnClickListener, OnItemSelectedListener{
int orientation;
DataBaseHelper myDbHelper;
Cursor c3, c2;
SimpleCursorAdapter adapterData;
int index = 0;
Spinner s[] = new Spinner[5];
TableRow row;
#SuppressWarnings("static-access")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myDbHelper = new DataBaseHelper(this);
//-----------Customized Adapter for Specialties----Database binded//
String[] columns2 = {myDbHelper.KEY_ID, myDbHelper.KEY_TITLE};
String table2 = myDbHelper.DB_TABLE_NAME;
c2 = myDbHelper.getHandle().query(table2, columns2, "type = 'SuperTab'", null, myDbHelper.KEY_TITLE, null, myDbHelper.KEY_TITLE);
startManagingCursor(c2);
String[] from = new String[]{myDbHelper.KEY_TITLE};
int[] to = new int[]{android.R.id.text1};
adapterData =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c2, from, to );
adapterData.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//-----------Customized Adapter for Location-----Database binded--//
String[] columns3 = {myDbHelper.KEY_ID, myDbHelper.KEY_LOCATION};
String table3 = myDbHelper.DB_TABLE_NAME_LOCATION;
c3 = myDbHelper.getHandle().query(table3, columns3, null, null, myDbHelper.KEY_LOCATION, null, null);
startManagingCursor(c3);
String[] from3 = new String[]{myDbHelper.KEY_LOCATION};
int[] to3 = new int[]{android.R.id.text1};
SimpleCursorAdapter adapterData3 =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c3, from3, to3 );
adapterData3.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//--------------------------------------------------------------//
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.specialty_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterData);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
adapter = ArrayAdapter.createFromResource(
this, R.array.office_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapterData3);
Button search = (Button)this.findViewById(R.id.Search);
search.setOnClickListener(this);
Button searchNearMe = (Button)this.findViewById(R.id.Near_Me);
searchNearMe.setOnClickListener(this);
spinner.setOnItemSelectedListener(this);
orientation = getResources().getConfiguration().orientation;
s[index] = new Spinner(this);
// s[index].setOnItemSelectedListener(this);
row = new TableRow(this);
}
#SuppressWarnings("static-access")
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
TextView tv = (TextView)this.findViewById(R.id.spinnerText2);
Log.w("ID: ", "index=" + adapterData.getItemId(pos) + " " + c2.getCount() + " " + id + " callee " + view);
String sql = "sql" + id ;
c2 = myDbHelper.getHandle().rawQuery(sql, null);
Log.w("ID Adapter: ", "index=" + adapterData.getItemId(pos) + " " + c2.getCount());
int thisOrientation = getResources().getConfiguration().orientation;
if (thisOrientation != orientation) {
return;
}
//--------sets hierarchy spinner to corresponding database-----//
String[] from = new String[]{myDbHelper.KEY_TITLE};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter adapterDataNew =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c2, from, to );
adapterDataNew.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
Log.w("Adapter Data New", "index=" + adapterDataNew.getItemId(pos) + " " + adapterDataNew.getCount());
//------------------------------------------------------------//
//-----------------Table Row for Landscape mode---------------//
TableLayout tl = (TableLayout)this.findViewById (R.id.Table);
TableLayout.LayoutParams tlp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
tlp.weight = 1;
tlp.setMargins(20, 15, 20, 0);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
//------------------------------------------------------------//
//------------------find Relative Layout by ID----------------//
RelativeLayout relative = (RelativeLayout)this.findViewById(R.id.rlay);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.BELOW, R.id.spinner);
p.setMargins(15, 5, 15, 5);
//------------------------------------------------------------//
if (orientation != getResources().getConfiguration().ORIENTATION_LANDSCAPE) {
if (c2.getCount() > 0) {
relative.removeView(s[index]);
relative.addView(s[index], android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
s[index].setVisibility(view.VISIBLE);
s[index].setPromptId(R.string.Sub);
s[index].setAdapter(adapterDataNew);
s[index].setLayoutParams(p);
tv.setPadding(10, 50, 10, 0);
Log.w("Index value ", " " + index);
}
else {
s[index].setVisibility(view.GONE);
relative.removeView(s[index]);
tv.setPadding(0, 0, 0, 0);
}
}
else {
if (c2.getCount() > 0) {
tl.removeView(row);
row.removeView(s[index]);
Log.w("Row Parent " + row.getParent()," tl child " + tl.getChildCount());
tl.addView(row, index + 4 , tlp);
row.addView(s[index]);
Log.w("Row Parent After Add" + row.getParent()," tl child After Add" + tl.getChildCount());
row.setVisibility(view.VISIBLE);
s[index].setVisibility(view.VISIBLE);
s[index].setPromptId(R.string.Sub);
s[index].setAdapter(adapterDataNew);
Log.w("ID: Landscape mode", "index=" + adapterDataNew.getItemId(pos) + " " + adapterDataNew.getCount());
}
else {
s[index].setVisibility(view.GONE);
row.setVisibility(view.GONE);
row.removeView(s[index]);
tl.removeView(row);
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
#Override
public void onClick(View v) {
EditText et1 = (EditText)this.findViewById(R.id.entry);
EditText et2 = (EditText)this.findViewById(R.id.entry2);
String lastName = et1.getText().toString();
String firstName = et2.getText().toString();
if (lastName.length() == 0) {
lastName = "%";
}
if (firstName.length() == 0) {
firstName = "%";
}
Bundle bundle = new Bundle();
bundle.putString("LastName", lastName);
bundle.putString("FirstName", firstName);
switch(v.getId()) {
case R.id.Search:
Intent i = new Intent(this, Search.class);
i.putExtras(bundle);
startActivity(i);
c2.close();
c3.close();
break;
case R.id.Near_Me:
Intent j = new Intent(this, SearchNearMe.class);
startActivity(j);
}
}
}
Lets say,you have 3 spinners spinner_1,spinner_2 and spinner_3 then:
spinner_1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if(spinner_1.getSelectedItem().equals("Spin1-Item-1")){
{
// set adapter to spinner_2 here for "Spin1-Item-1" selected
}
else if(spinner_1.getSelectedItem().equals("Spin1-Item-2"))
{
// set adapter to spinner_2 for "Spin1-Item-2" not selected
}
else
{
// set adapter to spinner_2 for "Spin1-Item-3" not selected
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinner_2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if(spinner_2.getSelectedItem().equals("Spin2-Item-1")){
{
// set adapter to spinner_3 here for "Spin2-Item-1" selected
}
else if(spinner_2.getSelectedItem().equals("Spin2-Item-2"))
{
// set adapter to spinner_3 for "Spin2-Item-2" not selected
}
else
{
// set adapter to spinner_3 for "Spin2-Item-3" not selected
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});