Android Multi Spinner - android

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) {
}
});

Related

Problem with using depended spinner (Multiple spinner) in android

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.

Populate first spinner on the basis of second spinner

I want my page to have two spinners and want to populate the second spinner on the basis of selection of the first spinner . I took two arrays . The first array is or the 1st spinner and the three arrays are for the second spinner . On the value selected from the first spinner I want the second spinner to select the corresponding values .
I have also referenced
get selected value from second spinner on the basis of selected value of first spinner
in this post , the author has used three adapters for three arrays to populate the second spinner but I was thinking of using only two . Is it possible ?
Simple Android two spinner and submit example
This code isn't showing any errors but the app isn't opening .
Spinner spin,spin1;
String state[] = new String[]{"A","B","C"};
String A[]= new String[]{"Pink","Blue","Red","white"};
String B[]= new String[]{"Apple","Grapes","Banana","Orange"};
String C[]= new String[]{"River","Mountains","Tree","Flower"};
ArrayAdapter<String> adap;
ArrayAdapter<String> adap1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spin = findViewById(R.id.spin);
spin1 = findViewById(R.id.spin1);
adap = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,state);
spin.setAdapter(adap);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, ""+ state[i], Toast.LENGTH_SHORT).show();
if (state[i].equalsIgnoreCase("A")) {
adap1.clear();
adap1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, A);
spin1.setAdapter(adap1);
}
if (state[i].equalsIgnoreCase("B")) {
adap1.clear();
adap1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item,B);
spin1.setAdapter(adap1);
}
if (state[i].equalsIgnoreCase("C")) {
adap1.clear();
adap1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, C);
spin1.setAdapter(adap1);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
Check of null pointer exp -
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, "" + state[i], Toast.LENGTH_SHORT).show();
if (adap1 != null) {
adap1.clear();
}
if (state[i].equalsIgnoreCase("A")) {
adap1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, A);
spin1.setAdapter(adap1);
}
if (state[i].equalsIgnoreCase("B")) {
adap1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, B);
spin1.setAdapter(adap1);
}
if (state[i].equalsIgnoreCase("C")) {
adap1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, C);
spin1.setAdapter(adap1);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Remove adap1.clear(); from all if conditions

Get values from dynamic spinners

I am creating spinners dynamically when i click add button.but i dont know how to get the values from created dynamic spinners.I need to get values how many shirt selected, saree selected and jeans selected when i click a submit button
this is my code
buttonAdd = (Button)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
final List<String> dressArray = new ArrayList<String>();
dressArray.add("Select Dress");
dressArray.add("Shirt");
dressArray.add("Saree");
dressArray.add("Jeans");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, dressArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner dress = (Spinner) findViewById(R.id.dress);
dress.setAdapter(adapter);
final List<String> dresscountArray = new ArrayList<String>();
dresscountArray.add("Count");
dresscountArray.add("1");
dresscountArray.add("2");
dresscountArray.add("3");
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, dresscountArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner dresscount = (Spinner) findViewById(R.id.dresscount);
dresscount.setAdapter(adapter1);
buttonAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
Spinner dresscount = (Spinner)addView.findViewById(R.id.dresscount);
Spinner dress = (Spinner)addView.findViewById(R.id.dress);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
PickupOrder.this, android.R.layout.simple_spinner_item, dressArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dress.setAdapter(adapter);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
PickupOrder.this, android.R.layout.simple_spinner_item, dresscountArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dresscount.setAdapter(adapter1);
Button buttonRemove = (Button)addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
((LinearLayout)addView.getParent()).removeView(addView);
}});
container.addView(addView);
}});
Firstly define globally
String value1;
int value_position1;
And then call these methods inside onCreate after setting value in each Spinner
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
value_position1 = position;
value1 = parent.getSelectedItem().toString()
.trim();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
And when you call your submit button, use values of each String.
showallPrompt = "";
int Count = new_container.getChildCount();
try {
for (int cc = 0; cc < Count; cc++) {
View child = new_container.getChildAt(cc);
Spinner value = (Spinner)(child.findViewById(R.id.sp_dynamic));
String spin_value = value.getSelectedItem().toString();
showallPrompt += spin_value;
}
} catch (Exception e) {
}
Toast.makeText(MainActivity.this,
showallPrompt,
Toast.LENGTH_LONG).show();
}
}
Do like this on your button click...

Automatically Populating a Spinner Based On Previous Spinner - android

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);
}

Updating listview in Android

I've made a listview for some games, and when a game is deleted i'd like it to vanish in the listview. I'm trying to use adapter.notifyDataSetChanged(), but i can't get it to work, can you help me?
public static final String MY_SETTINGS = "MySettings";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DBHelpeR entry = new DBHelpeR(Loadmenu.this);
entry.open();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
setListAdapter(adapter);
entry.close();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setBackgroundResource(R.drawable.background);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> parent, final View view,
int position, long id) {
String gamename = ((TextView) view).getText().toString();
builder.setTitle("Slet " + gamename + "?");
builder.setItems(new CharSequence[]{"Slet"} , new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
DBHelpeR entry = new DBHelpeR(Loadmenu.this);
entry.open();
int game_id = entry.getGameID(((TextView) view).getText().toString());
Log.d("load",Integer.toString(game_id));
entry.deleteGame(game_id);
entry.close();
adapter.notifyDataSetChanged();
}
});
builder.show();
return true;
}
});
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
replace the above line with below :::
ArrayList<String> entries = entry.getGameNames();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entries);
and when you delete just dcall the below two lines again::
entries = entry.getGameNames();
adapter.notifyDataSetChanged();
Updated::
Again before calling adapter.notifyDataSetChanged(); call the below lines::
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, entry.getGameNames());
setListAdapter(adapter);
call
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
setListAdapter(adapter);
Again before calling
adapter.notifyDataSetChanged();
Note: make sure you have changed the array for the change to be visible.

Categories

Resources