Spinner selecting step by step depend on selected value - android

I have 3 spinners and depend on each other like that;
Category1
Category2
Category3
When user select Category1, 2.spinner should show that;
Category1-1
Category1-2
Category1-3
And user select Category1-2, 3.spinner should show that;
Category1-1-1
Category1-1-2
Category1-1-3
I implement this way, but it is too long
so i want to any suggestion for more efficient code
public class BookActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner sp1,sp2,sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
List<String> list = new ArrayList<String>();
list.add("Category1");
list.add("Category2");
list.add("Category3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
sp1.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
fillSpinnerList(parent.getItemAtPosition(position).toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void fillSpinnerList(String selectedSpinnerName){
if(selectedSpinnerName =="Category1" ){
List<String> list = new ArrayList<String>();
list.add("Category1-1");
list.add("Category1-2");
list.add("Category1-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
sp2.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category2" ){
List<String> list = new ArrayList<String>();
list.add("Category2-1");
list.add("Category2-2");
list.add("Category2-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
sp2.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category3" ){
List<String> list = new ArrayList<String>();
list.add("Category3-1");
list.add("Category3-2");
list.add("Category3-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
sp2.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category1-1" ){
List<String> list = new ArrayList<String>();
list.add("Category1-1-1");
list.add("Category1-1-2");
list.add("Category1-1-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
sp3.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category1-2" ){
List<String> list = new ArrayList<String>();
list.add("Category1-2-1");
list.add("Category1-2-2");
list.add("Category1-2-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
sp3.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category1-3" ){
List<String> list = new ArrayList<String>();
list.add("Category1-3-1");
list.add("Category1-3-2");
list.add("Category1-3-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
sp3.setOnItemSelectedListener(this);
}
}
}

You can refactor it like that. It's still long as a part of it can be generalised but it's more readable.
BookActivity
public class BookActivity extends AppCompatActivity {
Spinner sp1, sp2, sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
initSpinner1();
}
private void initSpinner1() {
final List<String> list = new ArrayList<>();
list.add("Category1");
list.add("Category2");
list.add("Category3");
initSpinner(sp1, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
initSpinner2(itemName);
}
});
}
private void initSpinner2(String selectedCategory) {
final List<String> list = new ArrayList<>();
switch (selectedCategory) {
case "Category1":
list.add("Category1-1");
list.add("Category1-2");
list.add("Category1-3");
break;
case "Category2":
list.add("Category2-1");
list.add("Category2-2");
list.add("Category2-3");
break;
case "Category3":
list.add("Category3-1");
list.add("Category3-2");
list.add("Category3-3");
break;
default:
break;
}
initSpinner(sp2, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
initSpinner3(itemName);
}
});
}
public void initSpinner3(String selectedCategory) {
final List<String> list = new ArrayList<>();
switch (selectedCategory) {
case "Category1-1":
list.add("Category1-1-1");
list.add("Category1-1-2");
list.add("Category1-1-3");
break;
case "Category1-2":
list.add("Category1-2-1");
list.add("Category1-2-2");
list.add("Category1-2-3");
break;
case "Category1-3":
list.add("Category1-3-1");
list.add("Category1-3-2");
list.add("Category1-3-3");
break;
default:
break;
}
initSpinner(sp3, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
// TODO
}
});
}
private void initSpinner(Spinner spinner, List<String> list, SpinnerListener.Callback callback) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final AdapterView.OnItemSelectedListener listener = new SpinnerListener(this, callback);
spinner.setOnItemSelectedListener(listener);
}
}
The implementation of the OnItemSelectedListener
public class SpinnerListener implements AdapterView.OnItemSelectedListener {
private final Context mContext;
private final Callback mCallback;
public SpinnerListener(Context context, Callback callback) {
mContext = context;
mCallback = callback;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String itemName = parent.getItemAtPosition(position).toString();
Toast.makeText(mContext, "YOUR SELECTION IS : " + itemName, Toast.LENGTH_SHORT).show();
mCallback.onResult(itemName);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing
}
public interface Callback {
void onResult(String itemName);
}
}
The code can be shorten a little bit if you use lambda function (Java 8). For instance:
initSpinner(sp2, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
initSpinner3(itemName);
}
});
can be written:
initSpinner(sp2, list, itemName -> initSpinner3(itemName));
or even shorter:
initSpinner(sp2, list, this::initSpinner3);
EDIT
Or you can do something like that by using String arrays instead of lists. You can export the methods to init the array into a separated file so it makes the code in the Activity lighter:
public class BookActivity extends AppCompatActivity {
Spinner sp1, sp2, sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
initSpinner1();
}
private void initSpinner1() {
final String[] list = SpinnerArrayInitializer.getSpinner1Array();
initSpinner(sp1, list, itemName -> initSpinner2(itemName));
}
private void initSpinner2(String selectedCategory) {
final String[] list = SpinnerArrayInitializer.getSpinner2Array(selectedCategory);
initSpinner(sp2, list, itemName -> initSpinner3(itemName));
}
public void initSpinner3(String selectedCategory) {
final String[] list = SpinnerArrayInitializer.getSpinner3Array(selectedCategory);
initSpinner(sp3, list, itemName -> {
// TODO
});
}
private void initSpinner(Spinner spinner, String[] list, SpinnerListener.Callback
callback) {
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final AdapterView.OnItemSelectedListener listener = new SpinnerListener(this, callback);
spinner.setOnItemSelectedListener(listener);
}
}
And the to initialise the arrays:
public interface SpinnerArrayInitializer {
static String[] getSpinner1Array() {
return new String[]{"Category1", "Category2", "Category3"};
}
static String[] getSpinner2Array(String selectedCategory) {
switch (selectedCategory) {
case "Category1":
return new String[]{"Category1-1", "Category1-2", "Category1-3"};
case "Category2":
return new String[]{"Category2-1", "Category2-2", "Category2-3"};
case "Category3":
return new String[]{"Category3-1", "Category3-2", "Category3-3"};
default:
return new String[0];
}
}
static String[] getSpinner3Array(String selectedCategory) {
switch (selectedCategory) {
case "Category1-1":
return new String[]{"Category1-1-1", "Category1-1-2", "Category1-1-3"};
case "Category1-2":
return new String[]{"Category1-2-1", "Category1-2-2", "Category1-2-3"};
case "Category1-3":
return new String[]{"Category1-3-1", "Category1-3-2", "Category1-3-3"};
default:
return new String[0];
}
}
}

Try this:
public class BookActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private final static int SP1_NUM_OF_OPTIONS = 3;
private final static int SP2_NUM_OF_OPTIONS = 3;
private final static int SP3_NUM_OF_OPTIONS = 3;
private final static String SP3_HINT = "<SELECT>";
Spinner sp1, sp2, sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
// Setup data list and adapter for sp1.
ArrayList<String> list = new ArrayList<>();
for(int i=1; i<=SP1_NUM_OF_OPTIONS; i++){
list.add("Category" + i);
}
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
// Set listeners for all spinners.
sp1.setOnItemSelectedListener(this);
sp2.setOnItemSelectedListener(this);
sp3.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
fillSpinnerList(parent.getId(), parent.getItemAtPosition(position).toString());
// Automatically do something different after last step is selected.
if(parent.getId() == R.id.sp3){
if(!parent.getItemAtPosition(position).toString().equals(SP3_HINT)){
// Do something
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
public void fillSpinnerList(int spinnerId, String selectedSpinnerName){
ArrayAdapter adapter;
if(spinnerId == R.id.sp1){
String[] list1;
list1 = getResources().getStringArray(getResources().getIdentifier(selectedSpinnerName, "array", getPackageName()));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list1);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
}else if(spinnerId == R.id.sp2){
ArrayList<String> list = new ArrayList<>();
list.add(SP3_HINT);
String[] list1;
list1 = getResources().getStringArray(getResources().getIdentifier(selectedSpinnerName, "array", getPackageName()));
list.addAll(Arrays.asList(list1));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
}
}
}
Add your Category in strings.xml:
<array name="Category1">
<item>Category1_1</item>
<item>Two</item>
<item>Three</item>
</array>
<array name="Category1_1">
<item>Category1_1_1</item>
<item>Category1_1_2</item>
<item>Category1_1_3</item>
</array>
<array name="Two">
<item>Category1_2_1</item>
<item>Category1_2_2</item>
<item>Category1_2_3</item>
</array>
<array name="Three">
<item>Category1_3_1</item>
<item>Category1_3_2</item>
<item>Category1_3_3</item>
</array>
<array name="Category2">
<item>Category2_1</item>
<item>Four</item>
<item>Five</item>
</array>
<array name="Category2_1">
<item>Category2_1_1</item>
<item>Category2_1_2</item>
<item>Category2_1_3</item>
</array>
<array name="Four">
<item>Category2_2_1</item>
<item>Category2_2_2</item>
<item>Category2_2_3</item>
<item>Category2_2_4</item>
</array>
<array name="Five">
<item>Category2_3_1</item>
<item>Category2_3_2</item>
<item>Category2_3_3</item>
<item>Category2_3_4</item>
<item>Category2_3_5</item>
</array>
<array name="Category3">
<item>Category3_1</item>
<item>Six</item>
<item>Seven</item>
</array>
<array name="Category3_1">
<item>Category3_1_1</item>
<item>Category3_1_2</item>
<item>Category3_1_3</item>
</array>
<array name="Six">
<item>Category3_2_1</item>
<item>Category3_2_2</item>
<item>Category3_2_3</item>
<item>Category3_2_4</item>
<item>Category3_2_5</item>
<item>Category3_2_6</item>
</array>
<array name="Seven">
<item>Category3_3_1</item>
<item>Category3_3_2</item>
<item>Category3_3_3</item>
<item>Category3_3_4</item>
<item>Category3_3_5</item>
<item>Category3_3_6</item>
<item>Category3_3_7</item>
</array>
Hope it helps!!

Related

Using HashMaps in spinners android studio

I am using dynamic and static spinner.
This is my code, how can I implement a HashMap to show what the user selects (values)?
public class DatosAutoActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner sp_marca, sp_modelo, sp_colores;
private TextView tvMarca, tvModelo, tvColor, tvPlacas;
private Button btn_enviarDatos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_auto);
sp_marca = (Spinner)findViewById(R.id.sp_marca);
sp_modelo = (Spinner)findViewById(R.id.sp_modelo);
sp_colores = (Spinner)findViewById(R.id.sp_colores);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,
R.array.array_marcas,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_marca.setAdapter(adapter);
sp_marca.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapterColor = ArrayAdapter.createFromResource(
this,
R.array.array_colores,
android.R.layout.simple_spinner_item);
adapterColor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_colores.setAdapter(adapterColor);
sp_colores.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
int[] marcas = {R.array.array_chevrolet, R.array.array_ford, R.array.array_honda,
R.array.array_nissan,R.array.array_renault, R.array.array_toyota,
R.array.array_volkswagen};
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,
marcas[position],
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_modelo.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
protected void onResume() {
super.onResume();
btn_enviarDatos = (Button)findViewById(R.id.btn_enviarDatos);
btn_enviarDatos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent siguiente = new Intent(DatosAutoActivity.this, VerificacionDatosActivity.class);
startActivity(siguiente);
}
else {
Toast.makeText(getApplicationContext(), "Debes llenar todos los campos", Toast.LENGTH_SHORT).show();
}
});
}
}
Using Hashmap hope this will help you.
Value for spinner
String[] spinnerArray = new String[array.size()];
HashMap<Integer,String> spinnerMap = new HashMap<Integer, String>();
for (int i = 0; i < array.size(); i++)
{
spinnerMap.put(i,array.get(i));
spinnerArray[i] = array.get(i);
}
Set value to spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Get value from spinner
String name = spinner.getSelectedItem().toString();
String id = spinnerMap.get(spinner.getSelectedItemPosition());

String Resources

i'm practising how to add an string to the addapter of the spinner. If i declare the string in the java activity, works perfectly, but if i do in the string.xml:
<string-array name="tabs">
<item>tab</item>
<item>tab1</item>
<item>tab2</item>
<item>tab3</item>
<item>tab4</item>
<item>tab5</item>
</string-array>
and in the java
ArrayAdapter<String> adapterr1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, R.array.tabs);
dont work.
what's the problem? Thanks
This is the full code, because i have problems whit the app (crash)
public class MainActivity extends AppCompatActivity {
Spinner OptionSpinner;
TextView textview;
String[] stabs= getResources().getStringArray(R.array.tabs);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OptionSpinner = (Spinner) findViewById(R.id.OptionSpinner);
textview = (TextView) findViewById(R.id.textview);
ArrayAdapter adapter1 = new ArrayAdapter(this, android.R.layout.simple_spinner_item, stabs);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OptionSpinner.setAdapter(adapter1);
OptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textview.setText("seleccionado: " + parent.getItemAtPosition(position));
if(position==1){
Intent IntentActT1 = new Intent(MainActivity.this, ActTab1.class);
startActivity(IntentActT1);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
String[] stabs= getResources().getStringArray(R.array.tabs);
ArrayAdapter adapterr1 = new ArrayAdapter(this, android.R.layout.simple_spinner_item, stabs);
Edited 1
public class MainActivity extends AppCompatActivity {
Spinner OptionSpinner;
TextView textview;
String[] stabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OptionSpinner = (Spinner) findViewById(R.id.OptionSpinner);
textview = (TextView) findViewById(R.id.textview);
stabs= getResources().getStringArray(R.array.tabs);
ArrayAdapter adapter1 = new ArrayAdapter(this, android.R.layout.simple_spinner_item, stabs);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OptionSpinner.setAdapter(adapter1);
OptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textview.setText("seleccionado: " + parent.getItemAtPosition(position));
if(position==1){
Intent IntentActT1 = new Intent(MainActivity.this, ActTab1.class);
startActivity(IntentActT1);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
The constructor ArrayAdapter<String>(Context, int, int) doesn't use the third argument as an array resource id; it uses it as the id of the TextView to use to display each item in the layout. Instead, you can pass getStringArray(R.array.tabs) as the third argument (or getContext().getStringArray(R.array.tabs), if this code is not in an Activity).

get selected value from second spinner on the basis of selected value of first spinner

I want to select value from second spinner on the basis of value selected in first spinner.For example my first spinner displays country name and second spinner displays city name of that respective country.The problem is that second spinner is always taking first value as selected.Example-first spinner is country name-India,pakistan,china and second spinner is cities name,so if i select india and my spinner is-delhi,up,punjab then it always get selected value as delhi always.When I change the selected value even the function onItemSelected is not calling again.Code for the same is-
public class LaunchCampaign1 extends Activity implements OnItemSelectedListener,OnClickListener
{
String[] countryStr = {"Select", "India", "Pakistan", "China"};
String[] states_india = {"Select", "Delhi", "UP", "Bihar"};
String[] states_china = { "Select","Shanghai", "Beijing", "Nanjing"};
String[] states_pak = { "Select","Lahor", "Islamabaad", "Punjab"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_campaign);
country=(Spinner)findViewById(R.id.spinnerCountry);
country.setOnItemSelectedListener((OnItemSelectedListener) this);
ArrayAdapter <String> c = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,countryStr);
c.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
country.setAdapter(c);
city=(Spinner)findViewById(R.id.spinnerCity);
city.setOnItemSelectedListener((OnItemSelectedListener) this);
city.setEnabled(false);
public void onItemSelected(AdapterView<?> arg0, View view, int position,long id)
{
if(arg0.equals(country))
{
city.setEnabled(true);
if(country.getSelectedItem().equals("India"))
{
ArrayAdapter <String> s1 = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,states_india);
s1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city.setAdapter(s1);
/*city.setSelection(position);
Log.e("pos",""+position);
String cityStr = (String) city.getSelectedItem();*/
String cityStr=(String) city.getSelectedItem();
Log.e("city",cityStr);
}
else if(country.getSelectedItem().equals("Pakistan"))
{
ArrayAdapter <String> s2 = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,states_pak);
s2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city.setAdapter(s2);
}
else if(country.getSelectedItem().equals("China"))
{
ArrayAdapter <String> s3 = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,states_china);
s3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city.setAdapter(s3);
}
}
}
}
Got the solution of my problem.I just need to implement the onItemSelectListener for second spinner also.Now the updated code is-
public class LaunchCampaign1 extends Activity implements OnClickListener,OnItemSelectedListener
{
String[] countryStr = {"Select", "India", "Pakistan", "China"};
String[] states_india = {"Select", "Delhi", "UP", "Bihar"};
String[] states_china = { "Select","Shanghai", "Beijing", "Nanjing"};
String[] states_pak = { "Select","Lahor", "Islamabaad", "Punjab"};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_campaign);
country=(Spinner)findViewById(R.id.spinnerCountry);
country.setOnItemSelectedListener((OnItemSelectedListener) this);
ArrayAdapter <String> c = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,countryStr);
c.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
country.setAdapter(c);
city=(Spinner)findViewById(R.id.spinnerCity);
city.setOnItemSelectedListener((OnItemSelectedListener) this);
city.setEnabled(false);
public void onItemSelected(AdapterView<?> parent, View view, int position,long id)
{
switch(parent.getId())
{
case R.id.spinnerCountry:
city.setEnabled(true);
if(country.getSelectedItem().equals("India"))
{
ArrayAdapter <String> s1 = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,states_india);
s1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city.setAdapter(s1);
}
else if(country.getSelectedItem().equals("Pakistan"))
{
ArrayAdapter <String> s2 = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,states_pak);
s2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city.setAdapter(s2);
}
else if(country.getSelectedItem().equals("China"))
{
ArrayAdapter <String> s3 = new ArrayAdapter <String> (this,android.R.layout.simple_spinner_item,states_china);
s3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city.setAdapter(s3);
}
break;
case R.id.spinnerCity:
String cityStr1=city.getSelectedItem().toString();
Log.e("city1",cityStr1);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
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 Data1Activity extends Activity {
String[] countryStr = { "India", "China","Pakistan"};
String[] states_india = { "Delhi", "UP", "Bihar"};
String[] states_china = { "Shanghai", "Beijing", "Nanjing"};
String[] states_pak = { "Lahor", "Islamabaad", "Punjab"};
Spinner country,city;
ArrayAdapter<String> adaptercountry;
ArrayAdapter<String> adaptercity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
country= (Spinner) findViewById(R.id.spinner1);
city = (Spinner) findViewById(R.id.spinner2);
adaptercountry = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,countryStr);
country.setAdapter(adaptercountry);
country.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if(position==0)
{
adaptercity = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,states_india);
}
else
if(position==1)
{
adaptercity = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,states_china);
}
else
if(position==2)
{
adaptercity = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,states_pak);
}
city.setAdapter(adaptercity);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}

notifyDataSetChanged not updating my spinner

I have 2 spinners with two different adapter's (adapter and adapter2). Based on my selection of my first adapter (adapter), I am populating my second spinner (adapter2). After changing the data in the first spinner I called for adapter2.notifyDataSetChanged(); but this is not updating my second spinner. Any ideas?
UPDATE: It is updating if I call for a new adapter and set it like this:
adapter2 = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, objectList);
playerSpinner.setAdapter(adapter2);
but I don't think this is the correct way of doing this....
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, sDefaultPositions);
positionSpinner.setAdapter(adapter);
adapter2 = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, objectList);
playerSpinner.setAdapter(adapter2);
positionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long arg3)
{
changeSpinnerView(parent.getItemAtPosition(pos).toString());
Log.i("YourTeam", "ItemSlected"+objectList.toString());
adapter2.notifyDataSetChanged();
}
});
private void changeSpinnerView(String position)
{
objectList = getResults(playerkey);
Collections.sort(objectList);
}
public ArrayList<String> getResults(int key)
{
BLLPlayer playerdatasource = new BLLPlayer(this);
playerdatasource.open();
ArrayList<PlayerBean> resultList = new ArrayList<PlayerBean>();
resultList = (ArrayList<PlayerBean>) playerdatasource.getAllFunctionList(key);
playerdatasource.close();
return getPlayerName(resultList);
}
private ArrayList<String> getPlayerName(ArrayList<PlayerBean> resultList)
{
ArrayList<String> nameList = new ArrayList<String>();
for (int iIndex = 0; iIndex < resultList.size(); iIndex++)
{
String beanName = resultList.get(iIndex).getName();
if (beanName.equals("1"))
{
beanName = "";
}
else
{
nameList.add(beanName);
}
}
return nameList;
}

How to get the value from onItemClick ListView in Android

I have a global variable myval which is of String type.
String[] Category={"----SELECT----","BEVERAGES","BREAKFAST","LUNCH","DINNER","DESSERTS","APPETIZERS & SIDES"};
String[] Beverage={"PEPSI","COKE","LASSI","FALOODA","BUTTER MILK","GREEN TEA","BADAM MILK","MASALA CHAI" };
String[] Breakfast={"SIRLOIN & EGG","CFS STEAK & EGG","T-BONE & EGG","TWO EGGS BREAKFAST","2EGG W/MEAT","BEL WAFFLE","BEL WAFFLE W/MEAT","BLUEBERRY CAKE","CAKES","FABULOUS FRENCH TST","MOONS","FRENCH TST"};
String[] Lunch={" CRAB CAKE SANDWICH","TUSCAN GRILLED CHICKEN PANINI","SOUTHWEST TURKEY CLUB"," LOBSTER ROLL","TUNA MELT"," FRENCH DIP","YOUR OWN SANDWICH"};
String[] Dinner={"DUBLIN BAY PRAWN","CRAB FROM BRITTANY","WHITE ASPARAGUS","BLEWIT MUSHROOM","JOHN DORY FISH","MONKFISH","VEAL SWEET BREAD","LAMB","PIGEON FRY"};
String[] Desserts={"ECHOURGNAC CHEESE","HAZELNUT","GARIGUETTE STRAWBERRY","MOUSSE & ZEST","APRICOT","CHOCOLATE"};
String[] Appetizers={"Greek Artichoke Spinach","Seafood Appetizers","Tapenade Flatbread","Cranberry Blue Cheese","Fig and Blue Cheese","Sun-Dried Tomato","Tropical Crab Rangoon"};
class GlobalClass extends Application {
public static String[] myval;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
spinner = (Spinner) findViewById(R.id.spinnerCategory);
l1=(ListView) findViewById (R.id.list);
b1=(Button)findViewById(R.id.button3);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button1);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, Category);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final ArrayAdapter<String> bever = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Beverage);
// Assign adapter to ListView
final ArrayAdapter<String> Breakf = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Breakfast);
final ArrayAdapter<String> lunc= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Lunch);
final ArrayAdapter<String> Dinn= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Dinner);
final ArrayAdapter<String> Dessert = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Desserts);
final ArrayAdapter<String> Appet= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Appetizers);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id){
String Text = parent.getSelectedItem().toString();
if(Text.equals("----SELECT----")) {
}
else if(Text.equals("BEVERAGES")){
l1.setAdapter(bever);
return;
}
else if(Text.equals("BREAKFAST")){
l1.setAdapter(Breakf);
return;
}
else if(Text.equals("LUNCH")){
l1.setAdapter(lunc);
return;
}
else if(Text.equals("DINNER")){
l1.setAdapter(Dinn);
return;
}
else if(Text.equals("DESSERTS")){
l1.setAdapter(Dessert);
return;
}
else if(Text.equals("APPETIZERS & SIDES")){
l1.setAdapter(Appet);
return;
}
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "SELECTED :: " +((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
long ii=(long) l1.getItemIdAtPosition((int) id);
//Get the value from listView click item
String[] S5=new String[]{a5};
//String[] S1=new String[]{s2};
GlobalClass.myval=S5;
});
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String tno = e1.getText().toString();
int tn = Integer.parseInt(tno);
Intent i=new Intent(getApplicationContext(),TicketActivity.class);
Bundle b=new Bundle();
b.putInt("Table No:", tn);
i.putExtras(b);
String et= e2.getText().toString();
int et1 = Integer.parseInt(et);
Bundle be=new Bundle();
be.putInt("Guest:", et1);
i.putExtras(be);
startActivity(i);
}
});
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent(HomeActivity.this,PaynowActivity.class);
startActivity(intent);
}
});
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent m=new Intent(HomeActivity.this,OrderinfoActivity.class);
startActivity(m);
}
});
}
}
How do I get the value from onItemClick in the ListView?
ArrayAdapter<String> adapter=new ArrayAdapter<String>(HotelActivity.this, android.R.layout.simple_list_item_1,Category);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
if(position>0){
Intent intent=new Intent(HotelActivity.this,NewList.class);
intent.putExtra("position", position);
startActivity(intent);
}
}
});
Create new Activity and declare listview in its xml file
NewList Activity:
public class NewList extends Activity{
ListView listView;
int pos=0;
ArrayAdapter<String> adapter;
String[] Beverage={"PEPSI","COKE","LASSI","FALOODA","BUTTER MILK","GREEN TEA","BADAM MILK","MASALA CHAI" };
String[] Breakfast={"SIRLOIN & EGG","CFS STEAK & EGG","T-BONE & EGG","TWO EGGS BREAKFAST","2EGG W/MEAT","BEL WAFFLE","BEL WAFFLE W/MEAT","BLUEBERRY CAKE","CAKES","FABULOUS FRENCH TST","MOONS","FRENCH TST"};
String[] Lunch={" CRAB CAKE SANDWICH","TUSCAN GRILLED CHICKEN PANINI","SOUTHWEST TURKEY CLUB"," LOBSTER ROLL","TUNA MELT"," FRENCH DIP","YOUR OWN SANDWICH"};
String[] Dinner={"DUBLIN BAY PRAWN","CRAB FROM BRITTANY","WHITE ASPARAGUS","BLEWIT MUSHROOM","JOHN DORY FISH","MONKFISH","VEAL SWEET BREAD","LAMB","PIGEON FRY"};
String[] Desserts={"ECHOURGNAC CHEESE","HAZELNUT","GARIGUETTE STRAWBERRY","MOUSSE & ZEST","APRICOT","CHOCOLATE"};
String[] Appetizers={"Greek Artichoke Spinach","Seafood Appetizers","Tapenade Flatbread","Cranberry Blue Cheese","Fig and Blue Cheese","Sun-Dried Tomato","Tropical Crab Rangoon"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylist);
listView=(ListView) findViewById(R.id.newlist);
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
pos=bundle.getInt("position");
}
if(pos==1){
adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,Beverage);
listView.setAdapter(adapter);
}
else if(pos==2){
adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,Breakfast);
listView.setAdapter(adapter);
}
else if(pos==3){
adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,Lunch);
listView.setAdapter(adapter);
}
else if(pos==4){
adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,Dinner);
listView.setAdapter(adapter);
}
else if(pos==5){
adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,Desserts);
listView.setAdapter(adapter);
}
else if(pos==6){
adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,Appetizers);
listView.setAdapter(adapter);
}
}
}
Hope this will help you.

Categories

Resources