Basically, I want to associate a "selected" option with an id, so instead of doing this (my current way):
Vector spinnerList = new Vector();
spinnerList.addElement("No");
spinnerList.addElement("Yes");
I'd be doing something like this (the Hashtable/Vector is just for Blackberry compatability):
String id = "3";
Hashtable spinnerMap = new Hashtable();
spinnerMap.put(id, "No");
spinnerMap.put(id, "Yes");
Currently, a selected "option" from the spinner prints out 0 or 1 (based on the "No", "Yes"). So, my question is, if I'm setting the spinners programatically from a map whose values I don't know (I just know ids), how do I do this?
Spinner spinner = new Spinner(this);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, spinnerList);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
System.out.println("Selected: " + arg2);
}
public void onNothingSelected(AdapterView<?> arg0) {
System.out.println("Nothing selected: " + arg0);
}
});
Your question is not very clear. What exactly do you want to accomplish?
If you just want to display different data than a simple list of strings I think you should consider creating a custom adapter.
Reverse your map, and you can do an easy lookup of the integer id based on the string returned.
int id = spinnerMap.get(spinner.getSelectedItem());
Related
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);
}
I'm currently working on creating an app in android studio. The problem I am facing is generating a number of "plain text" objects based on the number chosen in a spinner. I have included layout of the activity below.
layout of activity can be seen here
Once the "number of people" are picked, then the area to enter the peoples names will be generated based on that. Max number of people will be 4.
Any help on how to do this would be much appreciated!
I would suggest using an OnItemSelectedListener() on your spinner along with setting the setVisibility() of your 'person' fields.
This code will assume your minimum people to be 1. Each time a new value is selected from the spinner the fields will appear or disappear. Using GONE for visibility will hide the field but also remove the space used by it. Use INVISIBLE if you want to keep the space.
Also don't bother setting the visibility in the xml layout code as this can cause issues.
person1 = (EditText)findViewById(R.id.person1);
person2 = (EditText)findViewById(R.id.person2);
person3 = (EditText)findViewById(R.id.person3);
person4 = (EditText)findViewById(R.id.person4);
list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
spinnerValue = parent.getItemAtPosition(position).toString();
int value = Integer.parseInt(spinnerValue);
// Simpler logic for the visibility of the 'people' - kudos to RobCo for pointing this out//
person1.setVisibility(value>=1? view.VISIBLE:View.GONE);
person2.setVisibility(value>=2? view.VISIBLE:View.GONE);
person3.setVisibility(value>=3? view.VISIBLE:View.GONE);
person4.setVisibility(value>=4? view.VISIBLE:View.GONE);
/*
if (value == 1)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.GONE);
person3.setVisibility(View.GONE);
person4.setVisibility(View.GONE);
}
else if (value == 2)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.GONE);
person4.setVisibility(View.GONE);
}
else if (value == 3)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.VISIBLE);
person4.setVisibility(View.GONE);
}
else
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.VISIBLE);
person4.setVisibility(View.VISIBLE);
}
*/
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
Good luck.
You simply do it by setting the visibility of all the 4 EditTexts as false and set a listener to the spinner. And inside the listener add if else statement and depending upon the selection you can set the visibility on for the EditText fields.
I created a Data-Base table student which contains two fields like student_id and student_name. This table contains some data for student.
My actual problem is I want to set ID and name of student in spinner like in html select tag, so when select spinner item I must get this ID to get another data from database.
You can have two arraylist for name and id;
List<String> sIds = new ArrayList<String>();//add ids in this list
List<String> names = new ArrayList<String>();//add names in this list
Then you can retrive here inside spinner select. It will work even if two names are same in the spinner which may be the case:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int id = sIds.get(position);//This will be the student id.
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
To add values into Spinner you can do it something like this Test
public class Test extends Activity
{
ArrayList<String> InfoStudent = new ArrayList<String>();
ArrayList<String> IdStudent = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//Here you'll have to make a query to get ID and Name then with
InfoStudent.add("TheID" + "InfoStudentReturnedByQuery");
//TheID should go in IdStudent ArrayAdapter and InfoStudentReturnedByQuery should go in InfoStudent ArrayAdapter
// Then you create the arrayAdapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Test.this
,android.R.layout.simple_spinner_item,difficultyLevelList);
// Set the Adapter
spinner.setAdapter(arrayAdapter);
If you want to know what spinner is selected you should do something like this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"You Selected : "
+ TheMainAdapterOfStudents.get(i)+" Student ",Toast.LENGTH_SHORT).show();
}
This only it's a guide how to, hope it helps :)
1. Declare type Like:
public class Item
{
public long id;
public String name;
}
2. Fill spinner with data (Item[]):
Item[] data = new Item[3];
data[0] = new Item(1, "Item 0");
data[1] = new Item(2, "Item 1");
data[2] = new Item(3, "Item 2");
ArrayAdapter<Item> dataAdapter = new ArrayAdapter<Item>(this,android.R.layout.simple_spinner_item, data);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
3. Get your id where you need it:
Item item = (Item)spinner.getSelectedItem();
return item.id;
Assuming I am reading your list correctly, if you want to set an Id to your Spinner programically just use..
mSpinner.setId(int)
In this code replace mSpinner with the reference to your Spinner and int with the desired Id
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.
I have a spinner which contains dynamic data which is displayed over 2 lines. What I require help with is dislaying only part of the spinners value (ItemArrayName[i]) within the spinner text box.
To calrify in the popup when the spinner is clicked, I require the full text, however when the item has been select I only require the item name.
e.g.
Within the App:
Item Name
Within the spinner selection pop out:
Item Name
Atk = 10, Def = 10
Java Code:
ArrayList<String> ItemArrayList = new ArrayList<String>();
for(int i = 0; i < ItemArrayName.length; i++)
{
ItemArrayList.add(ItemArrayName[i] + "\nAtk = " + String.valueOf(ItemArrayAtk[i]) + ", Def = " + String.valueOf(ItemArrayDef[i]));
}
Spinner spnItem = (Spinner) view.findViewById(R.id.UseItem);
ArrayAdapter<String> adpItem = new ArrayAdapter<String> (context, R.layout.spinnerrow, ItemArrayList);
spnItem.setAdapter(adpItem);
spnItem.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
//String city = "The item is " + parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(), city, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
Thanks in advance
How about using a Hashtable to map what you display in the spinner to your more detailed popup string?
EDIT:
Here's a primitive and possibly non compiling modification to your code using a hashtable as described:
// EDIT #1: Create a hashtable to lookup stuff:
final Hashtable<String, String> vals = new Hashtable<String, String>();
for(int i = 0; i < ItemArrayName.length; i++)
{
vals.put(ItemArrayName[i], ItemArrayName[i] + "\nAtk = " + String.valueOf(ItemArrayAtk[i]) + ", Def = " + String.valueOf(ItemArrayDef[i]));
}
Spinner spnItem = (Spinner) view.findViewById(R.id.UseItem);
// EDIT #2: Extract the array of hash keys to show in your list:
ArrayAdapter<String> adpItem = new ArrayAdapter<String> context, R.layout.spinnerrow, vals.keySet().toArray(new String[vals.size()]));
spnItem.setAdapter(adpItem);
spnItem.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
// EDIT #3: retrieve the full string from the hashtable using "get":
String city = "The item is " + vals.get(parent.getItemAtPosition(position).toString());
//Toast.makeText(parent.getContext(), city, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
Try mapping your short text to your long text.
HashMap<String,String> itemValues = new HashMap<String,String>();
itemValues.add("short text","the full long text that pops up when item is selected");
String longTextToDisplay = itemValues.get(currentSelectedShortText);
Of course this is a simplified example and this could be made more flexible, but this is the basic idea. You're just saying "this short text goes with this long text."
Everyone makes this much harder than it has to be. If the data is displayed in the spinner already, you can grab it from there without having to refer to the backing data.
Assuming you have a LinearLayout containing the two textviews (call them tv1 and tv2) as your row layout for the spinner, and you want the value of tv2, you could do this:
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
TextView tvResult = (TextView) view.findViewById(r.id.tv2);
String city = tvResult.getText().toString();
}
EDIT
I misunderstood your question... that I know of there is no way to make the closed spinner box display text different from the actual selection within the spinner using an ArrayAdapter. If there is, I'd be interested in seeing/reading about it.
I can think of a way to do it with a CursorAdapter, but as I said above, I can't think of any way to manage it for an ArrayAdapter.
The one option I can think of would be to find the spinner class in the android source, copy it out and modify it to make your own spinner class that is capable of such a function.