I'm really close to getting my spinner to do something when an item is selected. I just can't figure out how to set up the onitemselectedlistener correctly. I think my problem is not knowing how to pass the arguments to my onItemSelected method. Help to get the final part of this working is very much appreciated.
Here is the code:
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String[][] testScoreList = new String[3][3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Load test scores into arraylist
nameArrayListMethod();
spinner.setOnItemSelectedListener(onItemSelected());
}
//This method loads test scores into an array and populates spinner
public void nameArrayListMethod (){
InputStreamReader InputSR = null;
BufferedReader BufferedRdr = null;
String thisLine = null;
AssetManager am = getAssets();
String[] SpinnerNames = new String[3];
try {
InputSR = new InputStreamReader(am.open("scoresdata/test_scores.txt"));
BufferedRdr = new BufferedReader(InputSR);
// open input stream test_scores for reading purpose.
int i = 0;
while ((thisLine = BufferedRdr.readLine()) != null) {
//System.out.println(thisLine);
String[] parts = thisLine.split(" ");
testScoreList[i][0] = parts[0];
testScoreList[i][1] = parts[1];
testScoreList[i][2] = parts[2];
SpinnerNames[i] = testScoreList[i][0]; //Extract first column for spinner
i = i +1;
}
BufferedRdr.close();
InputSR.close();
} catch (Exception e) {
e.printStackTrace();
}
spinner= (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, SpinnerNames);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
}
You can add data Tow ways
Method 1
if you have a simple one line data the use this method.
step 1
Add string array in string.xml file
<string-array name="ArrayName">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
<item>E</item>
<item>F</item>
</string-array>
add android:entries="#string/ArrayName" in your xml spinner component
and get selected value using String text = spinner.getSelectedItem().toString();
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "Value = "+spinner.getSelectedItem().toString();, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
Method 2
for using custom adapter HERE is complete tutorial
It looks like:
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
});
Try this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Related
I'm trying to get the position (number) of the spinner when selected to use it in another Activity that will display a different map each time depending on the item selected. when I run the application it crashes. this is the first Activity code:
public class TestProjectActivity extends Activity {
public Spinner spinner1;
public Integer number;
private Button valideButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MySpinner();
valide_button();
}
public void MySpinner() {
final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.num, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// Object item = parentView.getItemAtPosition(position);
TestProjectActivity.this.number = spinner1
.getSelectedItemPosition() + 1;
}
public void onNothingSelected(AdapterView<?> arg0) {// do nothing
}
});
}
public void valide_button() {
valideButton = (Button) findViewById(R.id.valide_button);
valideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TestProjectActivity.this,
MetroMapActivity.class);
startActivity(intent);
}
});
}
}
The way to get the selection of the spinner is:
spinner1.getSelectedItemPosition();
Documentation reference:
http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()
However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.
So you could change that line to:
TestProjectActivity.this.number = position + 1;
If that does not fix the problem, please post the error message generated when your app crashes.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = findViewById(R.id.button);
spinner = findViewById(R.id.sp_item);
setInfo();
spinnerAdapter = new SpinnerAdapter(this, arrayList);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//first, we have to retrieve the item position as a string
// then, we can change string value into integer
String item_position = String.valueOf(position);
int positonInt = Integer.valueOf(item_position);
Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
note: the position of items is counted from 0.
final int[] positions=new int[2];
Spinner sp=findViewByID(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText( arg2....);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
if (position ==0) {
if (rYes.isChecked()) {
Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
} else if (rNo.isChecked()) {
Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
}
}
This code is supposed to select both check boxes.
Is there a problem with it?
I have a fragment that creates controls at runtime, first create a spinner and then the second, the detail is in the second spinner depends on having the first selection.
As I can update the data of the second spinner depending on the selection of the first?
final Spinner Combo2 = new Spinner(FichaRutasVerif2SeccionSlideFragment.this.getActivity());
final Spinner Combo1 = new Spinner(FichaRutasVerif2SeccionSlideFragment.this.getActivity());
List<String> list = new ArrayList<String>();
list.add("TERRESTRE");
list.add("FLUVIAL");
list.add("AEREO");
final ArrayAdapter<String> adapterCombo = new ArrayAdapter<String>(FichaRutasVerif2SeccionSlideFragment.this.getActivity()
,android.R.layout.simple_spinner_item,list);
List<String> list2 = new ArrayList<String>();
list2.add("OP1");
list2.add("OP2");
final ArrayAdapter<String> adapterCombo2 = new ArrayAdapter<String>(FichaRutasVerif2SeccionSlideFragment.this.getActivity()
,android.R.layout.simple_spinner_item, list2);
if(listFormato.get(posicion).cSeccion.trim().equals("M"))
{
adapterCombo.setDropDownViewResource(R.layout.spinner);
Combo1.setAdapter(adapterCombo);
Combo1.setSelection(listFormato.get(posicion).iIndexCombo);
llTempZZ.addView(Combo1);
Combo1.setGravity(Gravity.CENTER);
llTempXX.addView(llTempZZ);
llTEMPADRE.addView(llTempXX);
pllh.addView(llTEMPADRE);
}
else if(listFormato.get(posicion).cSeccion.trim().equals("U")){
final Spinner Combo0 = new Spinner(FichaRutasVerif2SeccionSlideFragment.this.getActivity());
List<String> list3 =new ArrayList<String>();
list3.add("SI");
list3.add("NO");
ArrayAdapter<String> adapterCombo3 = new ArrayAdapter<String>(FichaRutasVerif2SeccionSlideFragment.this.getActivity()
,android.R.layout.simple_spinner_item, list3);
adapterCombo3.setDropDownViewResource(R.layout.spinner);
Combo0.setAdapter(adapterCombo3);
llTempZZ.addView(Combo0);
llTempXX.addView(llTempZZ);
//llTempXX.addView(llTempAA);
llTEMPADRE.addView(llTempXX);
pllh.addView(llTEMPADRE);
Combo0.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int pos, long id) {
if (pos == 0) {
pll2.setVisibility(View.VISIBLE);
}
else if(pos==1) {
pll2.setVisibility(View.GONE);
}
listFormato.get(posicion).vResultado = Combo0.getSelectedItem().toString();
RECORDCARDITEM_DAO.Actualizar(FichaRutasVerif2SeccionSlideFragment.this.getActivity(), listFormato.get(posicion));
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
else if(listFormato.get(posicion).cSeccion.trim().equals("T"))
{
adapterCombo2.setDropDownViewResource(R.layout.spinner);
Combo2.setAdapter(adapterCombo2);
//Combo1.setSelection(listFormato.get(posicion).iIndexCombo);
llTempZZ.addView(Combo2);
Combo2.setGravity(Gravity.CENTER);
llTempXX.addView(llTempZZ);
llTEMPADRE.addView(llTempXX);
//////TEXTOS
Combo2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int pos, long id) {
if(Combo2.getSelectedItemPosition()==0)
{
}
if (pos ==12) {
llTempAA.setVisibility(View.VISIBLE);
} else {
llTempAA.setVisibility(View.GONE);
}
listFormato.get(posicion).vResultado = Combo2.getSelectedItem().toString();
RECORDCARDITEM_DAO.Actualizar(FichaRutasVerif2SeccionSlideFragment.this.getActivity(), listFormato.get(posicion));
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
You can do something like this
Spinner firstSpinner = (Spinner) findViewById(R.id.first_spinner);
// You can set your first spinner values here if not set already, and then
firstSpinner.setOnItemSelectedListener(onFirstSpinnerChange(firstSpinner));
And the further add this
AdapterView.OnItemSelectedListener onFirstSpinnerChange(Spinner mySpinner) {
return new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// You can add this method to set the values of the second spinner in your activity
// You can use the position, or alternatively selectedItemView for this purpose to identify the selected item
setSecondSpinnerBasedOnFirstOnePositionSelected();
// Or you can just set your spinner in this block
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
};
}
I have a spinner with ten numbers 0-10 and I if someone picks a number I want him not to be able to pick the same value again. So inside ItemSelected I do the following with no result
#Override
public void onItemSelected(AdapterView<?> adapter, View v, int position, long id) {
// On selecting a spinner item
if (position > 0 && position!=tempPosition)
{
TeamSpinnerNumber = adapter.getItemAtPosition(position).toString();
tempPosition = position
}
}
Check this i worked out for you may it help you.
public class MainActivity extends AppCompatActivity {
ArrayList<String> mStrings;
ArrayAdapter<String> mStringArrayAdapter;
Spinner mSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinner = (Spinner) findViewById(R.id.spinner);
mStrings = new ArrayList<String>() {{
add("None");
add("one");
add("two");
add("three");
}};
mStringArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings);
mSpinner.setAdapter(mStringArrayAdapter);
mSpinner.setSelection(0);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String string = parent.getItemAtPosition(position).toString();
if (!string.equals("None"))
removeThisFromSpinner(string);
mSpinner.setSelection(0);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void removeThisFromSpinner(String s) {
mStrings.remove(s);
mStringArrayAdapter.notifyDataSetChanged();
}
}
try this, hope it helps :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "onItemSelected: "+position);
//checking the position of the selected spinner item, if the previous position is not the same then do something here
if(position>0 && position!=myPosition){
}
myPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
and don't forget to add global variable to the class :
int myPosition = 999; // the non existed position make it global variable
I have two spinners (day_spin and time_spin) in one Activity. I want to save the selected day_spin value into a variable. Is it possible to differenciate between the two spinners in the same Listener? Or do I have to write my own Listener class for each spinner?
Also I want to get the number of the selected item. For example I have String Array with 6 elements. I select number 3. How can I get the id?
day_spin = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter_day = ArrayAdapter
.createFromResource(this, R.array.spinner_day_array,
android.R.layout.simple_spinner_item);
adapter_day
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
day_spin.setAdapter(adapter_day);
day_spin.setOnItemSelectedListener(this);
time_spin = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter_time = ArrayAdapter
.createFromResource(this, R.array.spinner_time_array,
android.R.layout.simple_spinner_item);
adapter_time
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
time_spin.setAdapter(adapter_time);
time_spin.setOnItemSelectedListener(this);
This is my Listener:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
DAY = parent.getItemAtPosition(pos).toString();
TIME = parent.getItemAtPosition(pos).toString();
}
I hope you can help me!
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(parent.getId() == R.id.spinner1)
{
//do this
}
else if(parent.getId() == R.id.spinner2)
{
//do this
}
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
//parent.getItemAtPosition(pos);
//Spinner spnir = (Spinner)parent;
parent.getItemAtPosition(pos);
TextView tvReadValue = (TextView) findViewById(R.id.tvReadValue);
switch (parent.getId())
{
case R.id.spinDimension:
tvReadValue.setText("spinDimension" + pos);
break;
case R.id.speedDimension:
tvReadValue.setText("speedDimension" + pos);
break;
}
in onItemSelected method
int i = spinnerFirst.getSelectedItemPosition();
int j = spinnerSecond.getSelectedItemPosition();
String strName1 = yourFirstarray[i];
String strName2 = yourSecondarray[j];
try this...
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(parent.getId() == R.id.spinnerone)
{
// operations
}
else if(parent.getId() == R.id.spinnertwo)
{
//operations
}
}
Two Spinner in same class
I try a lot of this but at the last, I got a working Code.
state = findViewById(R.id.spinnerState);
country = findViewById(R.id.spinnerCountry);
List<String> categories = new ArrayList<String>();
categories.add("Select State");
categories.add("Andhra Pradesh");
categories.add("Arunachal Pradesh");
categories.add("Assam");
categories.add("Bihar");
categories.add("Chandigarh");
categories.add("Delhi");
categories.add("Goa");
categories.add("Gujarat");
categories.add("Haryana");
categories.add("Himachal Pradesh");
categories.add("Jammu and Kashmir union territory");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(SaveUser.this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
state.setAdapter(dataAdapter);
state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// can leave this empty
}
});
List<String> categories2 = new ArrayList<String>();
categories2.add("Select Country");
categories2.add("Afghanistan");
categories2.add("Albania");
categories2.add("Algeria");
categories2.add("India");
categories2.add("Andorra");
categories2.add("Angola");
categories2.add("Antigua and Barbuda");
categories2.add("Argentina");
categories2.add("Armenia");
// Div Spinner implementing onItemSelectedListener
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(SaveUser.this, android.R.layout.simple_spinner_item, categories2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
country.setAdapter(dataAdapter2);
country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// can leave this empty
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getId() == R.id.number_of_poket_spinner) {
NumberOfPokets item = (NumberOfPokets) adapterView.getSelectedItem();
Toast.makeText(this, item.getPokets(), Toast.LENGTH_LONG).show();
} else if (adapterView.getId() == R.id.select_pleats) {
PleatsModel item2 = (PleatsModel) adapterView.getSelectedItem();
Toast.makeText(this, item2.getPleats(), Toast.LENGTH_LONG).show();
}
}
I'm trying to get the position (number) of the spinner when selected to use it in another Activity that will display a different map each time depending on the item selected. when I run the application it crashes. this is the first Activity code:
public class TestProjectActivity extends Activity {
public Spinner spinner1;
public Integer number;
private Button valideButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MySpinner();
valide_button();
}
public void MySpinner() {
final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.num, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// Object item = parentView.getItemAtPosition(position);
TestProjectActivity.this.number = spinner1
.getSelectedItemPosition() + 1;
}
public void onNothingSelected(AdapterView<?> arg0) {// do nothing
}
});
}
public void valide_button() {
valideButton = (Button) findViewById(R.id.valide_button);
valideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TestProjectActivity.this,
MetroMapActivity.class);
startActivity(intent);
}
});
}
}
The way to get the selection of the spinner is:
spinner1.getSelectedItemPosition();
Documentation reference:
http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()
However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.
So you could change that line to:
TestProjectActivity.this.number = position + 1;
If that does not fix the problem, please post the error message generated when your app crashes.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = findViewById(R.id.button);
spinner = findViewById(R.id.sp_item);
setInfo();
spinnerAdapter = new SpinnerAdapter(this, arrayList);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//first, we have to retrieve the item position as a string
// then, we can change string value into integer
String item_position = String.valueOf(position);
int positonInt = Integer.valueOf(item_position);
Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
note: the position of items is counted from 0.
final int[] positions=new int[2];
Spinner sp=findViewByID(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText( arg2....);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
if (position ==0) {
if (rYes.isChecked()) {
Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
} else if (rNo.isChecked()) {
Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
}
}
This code is supposed to select both check boxes.
Is there a problem with it?