Android - Default option in spinner - android

How can i set a default option in a spinner?
I filled 3 spinners with differents querys, and maybe i just want to use 2 of that spinners, not the 3. So always is a value set in the spinner. How can i avoid a value? Cause maybe if a fill an array i can set a default option in position 0, but im filling spinners with querys.
I know spinners are made to have a value, so maybe i could put them a default value so in the onitemclicklistener i can avoid using that spinner with an if (valuespinnerselected = "Default" ) dont to anything

You can configure a label and a value for each index of the Spinner.
Think that the value -1 is the default value that you want to ignore. That way, i think that this piece of code can help you:
Spinner spinner = (Spinner)findViewById(R.id.spinner);
SpinnerItem item1 = new SpinnerItem();
item1.setText("Default Query");
item1.setValue(-1);
SpinnerItem item2 = new SpinnerItem();
item2.setText("Query1");
item2.setValue(10);
SpinnerItem item3 = new SpinnerItem();
item3.setText("Query 2");
item3.setValue(20);
SpinnerItem[] data = new SpinnerItem[3];
data[0] = item1;
data[1] = item2;
data[2] = item3;
ArrayAdapter<SpinnerItem> adapter = new ArrayAdapter<SpinnerItem>(this, android.R.layout.simple_spinner_item, data);
spinner.setAdapter(adapter);
Where SpinnerItem is the class:
public class SpinnerItem {
String text;
Integer value;
public String getText() {
return text;
}
public void setText(String text){
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value){
this.value = value;
}
public String toString() {
return text;
}
}
After that, you can get the selected item and see his value:
SpinnerItem item = (SpinnerItem) spinner.getSelectedItem();
if(item.getValue() == -1){
//do Something.
}
Hope this helped!

I think easiest would be to put a default item like you mentioned. It could be "Please select".

Related

Problem in unable to validate spinner must be click

Adapter.class
holder.txt_AddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String product_image = brandWiseProductArrayList.get(position).getProductImgPath();
int qty = Integer.parseInt(holder.edtxt_integer_number.getText().toString());
}
});
Here, When I am click this button must be asked to select spinner
Is there any way to validate spinner or put "select something" in the first position of a spinner which is filled by objArraylist
ProductSpinnerAdapter productSpinnerAdapter = new ProductSpinnerAdapter(context, brandWiseProductArrayList.get(position).getProductDetailsArrayList());
holder.spinner_product_details.setAdapter(productSpinnerAdapter);
Try this
String product_image = brandWiseProductArrayList.get(holder.spinner.getSelectedItemPosition()).getProductImgPath();
change holder.spinner to respective spinner variable.
Let me know if this works

Is it possible to store additional information to spinner items?

I create a dropdown using a spinner and an ArrayAdapter. Now I want to save additional information to a spinner item.
I would like to add an integer for the id to these items. This id should not be shown in the dropdown, but when I call spinner.getSelectedItem(), I would like to have the possibility to do something like int id = spinner.getSelectedItem().getExtraInteger();
class Dog {
int age;
public Dog(int age) {this.age = age;}
#override String toString() { return "TextToDisplayInAdapter"; }
public int customInt() { return age; }
}
then in your Activity/Fragment/Whatever
ArrayAdapter<Dog> adapter =
new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, dogs);
spinner.setAdapter(adapter);
// somewhere else
Dog dog = (Dog) spinner.getSelectedItem();
dog.customInt();

How to Disable the 2nd Spinner Item Which is selected Already in 1st Spinner in Android

I want to Convert the Languages. So i am using two Spinners one is "From Language" and Another one is for "To Language". If One Language is Selected in "From Language" Spinner, it shouldn't display (or it should be disabled) in 2nd spinner. how can i achieve it?
Ex. if i Select English in 1st Spinner, 2nd Spinner Shouldn't display English in its dropdown.
This is may not be the best way try this.
ArrayList<String> languages = new ArrayList<>();
languages.add("English");
languages.add("Hindi");
languages.add("Telugu");
languages.add("Tamil");
languages.add("Kannada");
languages.add("Malayalam");
// make a array list of languages
String option1 = null;
Spinner spinnerOption1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<String> adapterOpton1 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, languages);
spinnerOption1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOption1.setAdapter(adapterOpton1);
spinnerOption1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
option1 = adapterOpton1.getItem(position);
}
});
int selectedIndex;
for (String item : languages) {
if (item.equals(option1)) {
selectedIndex == languages.indexOf(item);
}
}
ArrayList<String> languages2 = languages;
languages2.remove(selectedIndex);
Spinner spinnerOption2 = (Spinner) findViewById(R.id.spinner2);
final ArrayAdapter<String> adapterOption2 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, languages2);
spinnerOption2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOption2.setAdapter(adapterOption2);
Explanation:
lets create a arraylist with languages
bind it to the adapter on the spinner, on selection to the spinner one keep a track of that selection, then find the index of the selection in the arraylist.
create second arraylist with the same languages and find and remove the user selected item, create an adapter and bind the data.
Hope it helps.
Use Hashmaps it will be easier. Create an Adapter that uses Key Values for populating adapter.
This is a snippet I found from another link on how to do that, in case you are not familiar
public class HashMapAdapter extends BaseAdapter {
private HashMap<String, String> mData = new HashMap<String, String>();
private String[] mKeys;
public HashMapAdapter(HashMap<String, String> data){
mData = data;
mKeys = mData.keySet().toArray(new String[data.size()]);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(mKeys[position]);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
String key = mKeys[pos];
String Value = getItem(pos).toString();
//do your view stuff here
return convertView;
}
}
Credit What adapter shall I use to use HashMap in a ListView
Now for your management of the adapters.
LanguageOneMap.put (all your keys 0-whatever) value (english-whatever)
LanguageTwoMap.put (same as above)
LanguageAllMap.put (same as above)
Adapter 1 selects Language Callback(languageSelectedFromOneKey){
LanguageTwoMap.clearAll
LanguageTwoMap.put (all again)
LanguageTwoMap.remove(languageSelectedFromOneKey)
LanguageTwoAdapter.notifyDataSetChanged()
}
The above is just pseudo code meant to give the idea, not exact copy and paste. Hope that is enough to get you going. There are many ways to skin this cat, you could even use the same list for both adapters. Then when one is selected from one or the other, set a property of "selectedOtherLanguage" in the opposite adapter, then in the GetView method if data.get(pos) == selectedFromOtherListItem return, don't draw.
Many ways to do this, just a matter of how you want to do it. Goodluck.

use the selected item of a spinner

I am little bit stuck and need some ideas of how can I use the information that is selected from the spinner.
first the spinner is populated via Web service, by this code on the Asynctask:
#Override
protected Void doInBackground(Void... unused) {
...
...
...
HttpTransportSE transportSE = new HttpTransportSE(URL);
try{
//Web service call
transportSE.call(SOAP_ACTION_BRING_NEEDS, envelope);
//create SoapPrimitive and obtain response
resultsRequestSOAP = (SoapObject)envelope.getResponse();
int intPropertyCount = resultsRequestSOAP.getPropertyCount();
strNeeds = new String[intPropertyCount];
for(int i= 0;i< intPropertyCount; i++)
{
//Format the information from the web service
Object property = resultsRequestSOAP.getProperty(i);
if (property instanceof SoapObject) {
SoapObject needsList = (SoapObject) property;
strNeeds[i] = needsList.getProperty("Descripcion").toString();
}
}
then on the postExecute I fill the spinner calling a method spinnerNeeds():
public void spinnerNeeds() {
//Needs Spinner Control
spnNeeds = (Spinner)findViewById(R.id.spnNeeds);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, strNeeds);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnNeeds.setAdapter(adapter);
spnNeeds.setSelection(1);
spnNeeds.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Todo
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
the thing is that the spinner is populated by the strNeeds[] with the property ("Descripcion"), but the web service response have 3 properties, and I need another property call "Codigo" so that information can be sended to another activity. How can I validate after choosing a option on the spinner that be validate with the "codigo" that I also need?
I was thinking on creating another String[] strCode and save the property "Codigo" value inside the FOR() as I did with the "Descripcion" property... but if I pick an option on the spinner how can I validate that strCode??
PD: The "Codigo" property do not contain ascendance values, for example the first value is not 1,2,3,4.... they have random values...
The answer will be quite complex, but once you understand it's very simple.
First you'll need to create an object say, NEED with 3 properties(Description, Codigo..)
Next, instead of using an arrayadapter of type String, use arrayadapter of type NEED.
Next, in your custom class NEED, override the toString() method such that it returns the value of the property that needs to be displayed in the spinner.
Now, the selected item will return the NEED object, from which you get the value of the 'Codigo' property.
class Need{
String description, codigo, property3;
public Need(String desc, String codigo, String prop3)
{
this.description = desc;//similarly for other 2 properties
}
#override
private String toString()
{
return this.description;
}
}
strNeeds = new Need[intPropertyCount];
for(){
strNeeds[i] = new Need();
}
ArrayAdapter<Need> adapter = new ArrayAdapter<Need>(this,android.R.layout.simple_list_item_1, strNeeds);

displaying objects in a spinner rather than just strings

I'm building a dialog with a spinner. When the dialog is done, it calls a method of the parent activity with a string argument - the argument being the string value that was selected.
My current approach:
I'm setting up the spinner's array adapter like so:
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
categoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
categoryNames is a string array. When the dialog is done, the selected categoryName is used as the parameter to the method call on the parent activity.
What I really want to do:
What I actually want is to display a list of Category objects. The Category class has 2 properties - categoryId and categoryName. The spinner should still display the categoryNames in the drop-down view, but when the dialog is done, it should be able to unambiguously tell which Category was selected, and call the parent activity's callback method with the categoryId of the category that was selected.
There can be multiple Categoryies with the same categoryName.
Question: How to do the above?
There are a couple different way to do what you want:
Store the extra data in the adapter, like a SimpleAdapter, SimpleCursorAdapter, or custom one.
Use a Collection of custom objects instead of Strings, simply override the toString() method to present user readable Strings in the Spinner.
You seem to want to do the second option, so here's a generic example:
class Category {
int id;
String name;
public Category(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}
Your ArrayAdapter is almost the same:
List<Category> categories = new ArrayList<Category>();
// Add new items with: categories.add(new Category(0, "Stack");
ArrayAdapter<Category> adapter =
new ArrayAdapter<Category>(getActivity(), android.R.layout.simple_spinner_item,
categories);
...
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Category category = parent.getItemAtPosition(position);
Log.v("Example", "Item Selected id: " + category.id + ", name: " + category.name);
}
public void onNothingSelected(AdapterView<?> parent) {}
});

Categories

Resources