Simple spinner get position specific value - android

I have a simple Spinner implemented as:
vehicle = json.getJSONArray("vehicle");
for(int i = 0; i < vehicle.length(); i++){
JSONObject c = vehicle.getJSONObject(i);
//put json obkject on variable
String id = c.getString("id");
String name = c.getString("name");
String capacity = c.getString("capacity");
String cost = c.getString("cost");
String v = name + " ("+capacity + " Liters)";
vehicleList.add(v);
// Set Spinner Adapter
mySpinner.setAdapter(new ArrayAdapter<String>(OrderDetails.this,android.R.layout.simple_spinner_dropdown_item,vehicleList));
// Spinner on item click listener
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
car = vehicleList.get(+position);
Toast.makeText(getApplicationContext(), car, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
car = null;
}
});
}
I wanted to grab the value of "ID" in the car variable. Is it possible with above implementation?
Thanks in advance.

try to replace your item click listener with this ...
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
int spinnerItem = spinner.getSelectedItemPosition();
car = vehicleList.get(spinnerItem);
Toast.makeText(getApplicationContext(), selectedId, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do here :|
}
});
//EDIT
you can create another list that hold values of IDs ... and then add values to it as vehicleList ...
idList.add(id);
and then just call when item is selected in spinner
String selectedId = idList.get(spinnerItem);

Returns the position selected.
mySpinner.getSelectedItem()
or
mySpinner.getSelectedItemPosition()

Related

Android: how get ID of an item selected in a spinner?

I have this private method to render a spinner in a fragment:
private void renderSpinner() {
List<String> spinnerArray = new ArrayList<String>();
for (int i = 0; i<mPromotionList.size(); i++) {
ModelPromotion modelPromotion = (ModelPromotion) mPromotionList.get(i);
String name_promotion = modelPromotion.getName();
int id_promotion = modelPromotion.getIdPromotion();
spinnerArray.add(name_promotion);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mBaseApp, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerPromotion.setAdapter(adapter);
mSpinnerPromotion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String name_promotion_selected = parent.getItemAtPosition(pos).toString();
//TODO REMOVE
Log.d(LOGTAG, "Il nome della promo selezionata รจ " + name_promotion_selected);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
As you can see, I have "ready" the id_promotion (It's the real value that I need)... And I know that I'm not adding (for now) at the List.
How I can get it, inside the onItemSelected?
Thank you very much
You can use the position of the selected item and use that to get the ID from the original list.
((ModelPromotion) mPromotionList.get(pos)).getIdPromotion()
Another option is to create a custom ArrayAdapter subclass that will accept ModelPromotion instead of String and override getItemId to return the idPromotion
An example about custom ArrayAdapter on Github.

Save spinner state even moved to another activity with Android

I want to save my spinner state even when I move to a different activity and come back to the page with the spinner, the state should be the same. I have no idea how to do it, I saw some examples on other threads on stack overflow but I don't understand them.
Here's my code:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
index = arg0.getSelectedItemPosition();
// storing string resources into Array
lang_list = getResources().getStringArray(R.array.language_list);
Toast.makeText(getBaseContext(), "You have selected : " + lang_list[index],
Toast.LENGTH_SHORT).show();
choice = spinner.getSelectedItem().toString();
// edit_cate.setText(choice);
final ImageView country_flag = (ImageView)findViewById(R.id.country);
String s=((TextView)arg1).getText().toString();
if(s.equals("English"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.eng_spinner));
if(s.equals("German"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.german_spinner));
if(s.equals("French"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.french_spinner));
if(s.equals("Spanish"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.spanish_spinner));
}
Thanks for the help.
You need to save state of your spinner so this would be helpful to you.
1.) Apply this after creating spinner object
spinner.setSelection(getPersistedItem());
2.) Create these methods according to you to save the state of your spinner selected item
private int getPersistedItem() {
String keyName = makePersistedItemKeyName();
return PreferenceManager.getDefaultSharedPreferences(this).getInt(keyName, 0);
}
protected void setPersistedItem(int position) {
String keyName = makePersistedItemKeyName();
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(keyName, position).commit();
}
private String makePersistedItemKeyName() {
return currentUserName + "_your_key";
}
3.) Set its state as the spinner selection changed:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View view, int position, long itemId) {
setPersistedItem(position);
} #Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });

converting selected spinner value to defined int variable : android

I have an android program in which there is a spinner. i am getting the selected spinner value. i am able to send it as json too.
The problem is i want to send 1 if option1 is selected , 2 if option two is selected and so on.
Is there a method the selected value is converted to int value of my choice before i send it as json ?
the code is
public void addItemsOnSpinner1() {
s1 = (Spinner) findViewById(R.id.spinnerL);
List<String> list = new ArrayList<String>();
list.add("Casual");
list.add("Earned");
list.add("Compensatory");
list.add("Without Pay");
list.add("Sick Leave");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(dataAdapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
// Toast.makeText(getBaseContext(), s5.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
final String SelectedLeave = s1.getSelectedItem().toString();
balanceLeavesLeft();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
the 3rd param is the position of selected item of your spinner:
It's arg2 in your code
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
// Toast.makeText(getBaseContext(), s5.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
final String SelectedLeave = s1.getSelectedItem().toString();
balanceLeavesLeft();
}
--> So you just need print out: (arg2+1)
tauitdnmd, answer is good but, the best way should be that you have an Entity class Opion as example and you have the string value for it and the int value of the selected row :) that's how is done usually.
public class YourOptionClass {
private String optionName;
private int optionValue;
//construktor
//getter and setter
//to string
}
And you populate your spinner with this class.
public void onItemSelected(AdapterView<?> arg0, View arg1,int pos, long arg3){
int option = YourAdapterClass.getItem(pos).getOptionValue();
}

how to find the position of item in a AutoCompletetextview filled with Array

I have an array (array1 with States) and AutoCompleteTextview in which I'm filling it with array1. When I select the value from AutocompleteTextView I select a state from AutoCompleteTextView Dropdown
What I want is to get the position of the item from array1 which I've selected.
What I've tried is OnClickEvent of AutocompelteTextView.
STATE.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String) parent.getItemAtPosition(position);
String num = selection;
}
});
It ss giving me the value which I selected from dropdown but i want to get the position of the value in array1. For Example I have an array of size 4, like array1 = {A,B,C,D}, and if I select B it should return me B position in Array i.e 2.
I hope I made it clear. Thanks in advance.
Use the position variable in the onItemClick.
STATE.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String) parent.getItemAtPosition(position);
int pos = -1;
for (int i = 0; i < yourarray.length; i++) {
if (yourarray[i].equals(selection)) {
pos = i;
break;
}
}
System.out.println("Position " + pos); //check it now in Logcat
}
});
Use List instead of Array. Implement onItemClickListener for AutoCompleteTextView, then use indexOf on your list to find the index of selected item.
actvCity.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int index = cityNames.indexOf(actvCity.getText().toString());
// Do Whatever you want to do ;)
}
});
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView txtvw=(TextView) view;
String str=txtvw.getText().toString();
int index = contactNames.indexOf(str);
}
Item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//// id contains item if from database
ItemNoSelected = id;
}
});
id is from database, we can use that
You can find the parent string in the clickItem listener.
OSchools in this case is the custom ArrayList.
Object item = parent.getItemAtPosition(position);
for(OSchools d : data){
Log.e("name",d.getName());
String name = d.getName();
if(d.getName() != null && name.contains(item.toString())){
ID = d.getID();
}

setting itemListener of variable number of spinners

int numberofSpinner = TransportResult.Transfers.size();
Spinner spin=null;
for(int i=0;i<numberofSpinner;i++)
{
spin = new Spinner(this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,1);
spinLayout.addView(spin,p);
spin.setId(i);
Transfer transfer = TransportResult.Transfers.get(i);
ArrayList<CharSequence> s = new ArrayList<CharSequence>();
for( Line l : transfer.TransferLine)
{
s.add(l.ShortName+" - "+Helper.FindTransportTypeText(l.LineType));
}
adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item,s);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
}
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if(parent.getId()==0){
System.out.println("spin 1 is called");
String str = (String)parent.getSelectedItem();
}else if(parent.getId()==1){
System.out.println("spin 2 is called");
String str = (String)parent.getSelectedItem();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
If the number of spinner is more than 1, only the last spinner is triggered. For example; i have 3 spinner on screen, when i select the item of first or second spinner, the listener is never triggered. Only the third spinner triggers the listener. How can i solve that?
Thank you
UPDATE
when you use more than one spinner then setid for each spinner spin.setId(int) .and you can check id in OnItemSelected method. Mind that when you set OnitemSelected first time onItemSelected is called.
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if(parent.getId()==1){
System.out.println("spin 1 is called");
String str = (String)parent.getSelectedItem();
}else if(parent.getId()==2){
System.out.println("spin 2 is called");
String str = (String)parent.getSelectedItem();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});

Categories

Resources