How to set selected item for Spinner in Android - java

In an Android app, I have a SpinnerAdapter that I am using to display expiration years of credit cards. My variable expirationYears contains an array of Strings with years from "2020" to "2029". It was declared as String[] expirationYears = new String[10]; and then with a function I set the ten years as Strings, from current year and then the nine subsequent years after that for a total of ten elements in the array. When I run it, this is what I see:
Everything is perfect so far. The only problem is that when as you see in the image above, 2020 is the year selected by default. That is the first element in the expirationYears array. But I want to set 2021 as default (the second element of the array). This is what my code has:
Spinner spinnerYearCreditCardPayment;
SpinnerAdapter creditCardYearAdapter = new SpinnerAdapter(Payment.this, expirationYears);
creditCardYearAdapter
.setDropDownViewResource(android.R.layout.spinner_dropdown_item);
spinnerYearCreditCardPayment.setAdapter(creditCardYearAdapter);
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
..........
});
I was expecting to have some property available to define which element I want to show by default. Something like creditCardYearAdapter.setSelectedItem(INDEX_NUMBER). But that property does not exist. Do you know how I could set the default selected item so that it is not the first element of the array (2020) but the second (2021)? Thank you.
UPDATE 1:
Following The_Martian's answer, this was what I did:
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg0.setSelection(1);
cardYear = (String) spinnerYearCreditCardPayment
.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Now I correctly see the second element of the array ("2021") as the default selection.
The problem is that when I use arg0.setSelection(1);, I choose another year and it does not respond. The selected year remains "2021" even thought I am trying to change the year.

You can do similar to the following. I am just giving you an idea here.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.setSelection(position + 1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Try this snippet
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
int seleccion=parent.getSelectedItemPosition();
spinner.setSelection(position)
});
}

You can select the spinner item based on value instead of position. Can refer the example below-
String value = "to be selected value";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (value != null) {
int spinnerPosition = adapter.getPosition(value);
mSpinner.setSelection(spinnerPosition);
}

Related

how I can hide the element with index 0 from dropdown list in spinner

Please tell me how can I hide the item at index 0 from the dropdown in the spinner in Android Studio? I am using this code, it works, but when I open the list, it shows at the bottom. That is, it is focused on the elements below. what do i need to change?
SpinnerName = (Spinner) v.findViewById(R.id.spinner1);
ArrayList<String> names = new ArrayList<>();
names.add(0, "SELECT");
names.add(1, "Name1");
names.add(2, "Name2");
final int listsize = names.size()-1;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names){
#Override
public int getCount() {
return(listsize);
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerName.setAdapter(adapter);
adapter.setDropDownViewResource(R.layout.spinner_list);
SpinnerName.setSelection(listsize);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
....
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
SpinnerName.setSelection(listsize);
your problem is here! you are passing the total list size number and
that where you are doing wrong, because setSelection method use to
show default index of spinner.
you can simply do that SpinnerName.setSelection(1); that would give you the fist spinner item unless showing the names.add(0, "SELECT"); item

Android Multiple Spinner

I'm sure I'm missing something simple, but I am having some logic issues with my code. I am working on a converter app. I will be using two spinners to select between to do conversions. Ex. inches to feet. I am using two simple methods to test before fleshing out all of the code. Right now if I select the value for SpinnerA in the app first, and then select the value for SpinnerB, it doesn't calculate. If I select SpinnerB first and then SpinnerA, it works. What am I missing?
spinnerA = (Spinner)getView().findViewById(R.id.spinnerA);
spinnerB = (Spinner)getView().findViewById(R.id.spinnerB);
adapterA = ArrayAdapter.createFromResource(getContext(),
R.array.conversions, android.R.layout.simple_spinner_item);
adapterA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapterB = ArrayAdapter.createFromResource(getContext(),
R.array.conversions, android.R.layout.simple_spinner_item);
adapterB.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerA.setAdapter(adapterA);
spinnerB.setAdapter(adapterB);
spinnerA.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tempA = parent.getItemAtPosition(position).toString();
if (tempA.equals("Inches") && tempB.equals("Centimeters")){
textView.setText(String.valueOf(halfMyNum(100)));
}
else if (tempA.equals("Centimeters")){
if (tempB.equals("Inches")){
textView.setText(String.valueOf(doubleMyNum(12)));
}
}
else{
textView.setText("Please select a valid option");
}
//Toast.makeText(getContext(), parent.getItemAtPosition(position)+ " Selected"
//, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerB.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tempB = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
When you are selecting an item from spinnerA first, tempA is initialized and item listener for spinnerA is called but tempB is not yet initialized.
Then, when you select item from spinnerB, tempB is initialized and item listener for spinnerB is called. In your case, you only called the method in item listener method for spinnerA, so when you select item from spinnerB nothing actually executes. One possible solution is to call the desired method in item listener for spinnerB as well.

Set visibility TableLayout based item selected on Spinner

I want to make Spinner to set Visibility of table, i have 2 Array String "cuboid and cylinder". if i select Cuboid , cubeT table is visible and cyclinderT table is Invisible. and if i select Cylinder , cylinderT table is Visible and cubeT is Invisible.
Sample code welcome. Thank you for your time.
You can set an OnItemSelectedListener to your Spinner then using the int position argument to decide what action to take.
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (position) {
case Cuboid:
cubeT.setVisibility(View.VISIBLE);
cylinderT.setVisibility(View.GONE);
break;
....
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) { }
});
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String text = ((Spinner)spinner).getSelectedItem().toString();
if (Intrinsics.areEqual(text, "Cuboid")) {
//Your code here to set your "table" as cubeT if it's image in imageview
//if it's a "tableLayout" you may create 2 different layouts included and..:
setContentView(R.layout.your_cubeT_layout);
} else if (Intrinsics.areEqual(text, "Cylinder")) {
setContentView(R.layout.your_cyclinderT_layout);
}
} //when it comes to use different layouts on the same activity, generally suggestions made over fragments to make your code more dynamic but i don't know how to do that...
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
I'm not using java since years so i might code bad... So no warranty!

Displaying the selected string from Android Spinner

String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
spTimeConsegna = (Spinner)
rootView.findViewById(R.id.timeChooseConsegna);
adapterChooseTimeConsegna = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chooseTime);
adapterChooseTimeConsegna.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spTimeConsegna.setAdapter(adapterChooseTimeConsegna);
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
I want to save the selected value of the spinner in the chooseTimeConsegna String, but it always saves the first value of the chooseTime string array indifferently what is choosen in the spinner. Why?
I think you are doing this in onCreate method, so it's only called when that activity is started, not every time you select things on spinner. Try something like this:
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String chooseTime[] = {"7.00 - 9.00", "9.00 - 11.00", "11.00 - 13.00", "13.00 - 15.00", "15.00 - 17.00", "17.00 - 18.30" };
chooseTimeConsegna = chooseTime[position];
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
This method is gonna be called every time you select something on your spinner, and argument position is the position of the selected item in the spinner.
Replace:
chooseTimeConsegna = chooseTime[spTimeConsegna.getSelectedItemPosition()];
With:
spTimeConsegna.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
chooseTimeConsegna = chooseTime[position];
}
});
You should be good to go.

Android spinners: How to write java code for them?

I am trying to make a GPA calculator. I have a bunch of spinners in two columns. 7 in each. I have put in an array of strings to be displayed in the drop down list. Now, I want to write code in java for saying if the user selects "four" from the drop down list, then the input should be considered as number 4 later to multiply it with for example if the user chose grade A, then to multiply with 4. How do I do this? I created an array adapter but it's not working. i am getting "Nan" as the answer. I have looked it up and it says Nan is displayed when the number is undefined. Any help would be appreciated. Thank you!
Should I be using some kind of onClickListener like I used for my button? How does the computer know that it has to equate gradepoint to 4 if the user picks grade A?
This is what I did (which obviously is wrong):
if(spinner1.getSelectedItem().equals("A+")) gradepoint1=4.00;
if(spinner1.getSelectedItem().equals("A")) gradepoint1=4.00;
if(spinner1.getSelectedItem().equals("A-")) gradepoint1=3.67;
if(spinner1.getSelectedItem().equals("B+")) gradepoint1=3.33;
if(spinner1.getSelectedItem().equals("B")) gradepoint1=3.00;
if(spinner1.getSelectedItem().equals("B-")) gradepoint1=2.67;
if(spinner1.getSelectedItem().equals("C+")) gradepoint1=2.33;
if(spinner1.getSelectedItem().equals("C")) gradepoint1=2.00;
if(spinner1.getSelectedItem().equals("C-")) gradepoint1=1.67;
if(spinner1.getSelectedItem().equals("D+")) gradepoint1=1.33;
if(spinner1.getSelectedItem().equals("D")) gradepoint1=1.00;
if(spinner1.getSelectedItem().equals("D-")) gradepoint1=0.67;
if(spinner1.getSelectedItem().equals("F")) gradepoint1=0.00;
if(spinner1.getSelectedItem().equals("ABS")) gradepoint1=0.00;
I suggest you do something like this:
Before you're oncreate:
float[] gradeValues = { 4f, 3.67f, 3.33f, 3.00f, 2.67f, 2.33f, 2.00f,1.33f,1.00f,0.67f,0.00f,0.00f};
String [] gradeAlpabetic = {"A+","A","A-","B+","B","B-","C+","C","C-","D+","D","D-","F","ABS"};
Here the first value, 4f, has the position 0, and the next has 1 and so on.
The value "A+" will be at position 0 on the spinner, so this way we know which grade goes with which grade value.
In onViewCreated or OnCreate:
ArrayAdapter<String> gradesArrayAdap = new ArrayAdapter<String>(
getActivity(), R.layout.spinnerlayout, gradeAlphabetic);
gradesSpinner.setAdapter(GradesArrayAdapter);
gradeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
getGrades();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Then you put this outside the onViewCreated/onCreate.
public void getGrades(){
String grade = gradeSpinner.getSelectedItemPosition();
float theGrade = Float.parseFloat(gradeValue(grade);
System.out.println("Your grade in float is: " + theGrade);
}
Hope it helps.
You can have a hashmap of the values and then select the value based on the selected item
HashMap<String, Double> mGrades;
public void test(){
Spinner spinner1 = new Spinner(this);
mGrades = new HashMap<String, Double>();
mGrades.put("A+", 4.00);
mGrades.put("A", 4.00);
//Etc.....
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mGrades.keySet().toArray(new String[0]));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(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)
Log.d("TAG", String.valueOf(mGrades.get(mGrades.keySet().toArray()[pos])));
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
It may be a bit slower then using some other method, but hey. Its something simple.

Categories

Resources