where to declare array of items for the spinner - android

I have been going through spinners for my application but I don't know where to declare the items that are to be shown in the spinner i.e either I declare them in the string.xml or in my main_activity like this ..
String[] data = { "Hello", "There", "I", "Am", "Taking", "Values" };
Which method is best to use and why?

After declaring values in resources tag in strings.xml like below:
<string-array name="spinner_values">
<item>a</item>
<item>b</item>
</string-array>
you can use entries attribute in spinner tag in your xml layout, instead of use it pro-grammatically in java file. Like below:
<Spinner
android:id="#+id/my_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spinner_values" />

Declaring the array in string.xml is better because:
If you want to translate your app into another language, you just
need this one file which has all the arrays and strings that your app uses.
If you have to make any changes to any string/array, you know by default where to look for(All at one place).
Re-use is possible using this way. In any other activity you can just use from there, instead of declaring again.

you can try in this way ....
public void addItemsOnSpinner1() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("Small");
list.add("Medium");
list.add("Large");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
apply = (Button) findViewById(R.id.apply);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
apply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(String.valueOf(spinner1.getSelectedItem()).equals("Small"))
{
// your code
}
if(String.valueOf(spinner1.getSelectedItem()).equals("Medium"))
{
// your code
}
else if(String.valueOf(spinner1.getSelectedItem()).equals("Large"))
{
// your code
}
}
});

If content of your spinner is fixed then declare it in String.xml . its best practice

You should declare array in strings.xml
<string-array name="data">
<item>Hello</item>
<item>There</item>
<item>I am</item>
<item>Taking</item>
</string-array>
and obtain values in activity
String [] array =getResources().getStringArray(R.array.data);

Related

How to delete item from spinner added via entries in layout xml?

I have this array in my strings.xml :
<string-array name="lst_addressTypes">
<item>FISCAL</item>
<item>NAP</item>
<item>SUCURSAL</item>
<item>ALMACEN</item>
<item>OFICINA</item>
<item>OTRO</item>
</string-array>
And I have this Spinner in my layout XML:
<Spinner
android:id="#+id/cboTipoDireccion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/lst_addressTypes" />
And I want to delete some items programmatically.
I tried to do this like:
spinnerObject.removeViewAt(0)
but this threw an `InvalidOperationException
You can add String[] or ArrayList<String> for entries in your activity.
Adding:
List<String> entriesList = new ArrayList<>();
// add items into spinner dynamically
public void addItemsOnSpinner() {
String[] entries = getResources().getStringArray(R.array.lst_addressTypes);
entriesList = new ArrayList<String>(Arrays.asList(entries));
Spinner spinner = (Spinner) findViewById(R.id.cboTipoDireccion);
ArrayAdapter spinnerAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, entriesList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
}
Removing:
entriesList.remove(0);
spinnerArrayAdapter.notifyDataSetChanged();

Android Spinner not displaying array, but showing places

I've been trying to figure out how to make my spinner work for days straight now, and can't find anything to help me. My spinner doesn't show the values. The spinner opens up, and the spaces for each value is there, but they're all blank. I have tried using an ArrayList<String>, and also a String[] array, neither of which made a difference, but do I need to use one over the other? I have tried many different types of ArrayAdapters, but none of them have worked. The one in my code below is the one that works the closest, (as described above), and the other 3 are suggestions I saw online. I think my main problem is in my array adapter, but I'm not certain.
Here is my java class
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
engineSpinner = (Spinner)findViewById(R.id.rockets);
engineNameList = StagesData.getEngineNameList();
engStrList = engineNameList.toArray(new String[engineNameList.size()]);
adapter = new ArrayAdapter<String>(InfoActivity.this, android.R.layout.simple_spinner_item, engStrList);
// adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, R.array.array_engines);
// adapter = new ArrayAdapter<String>(InfoActivity.this, android.R.layout.simple_dropdown_item_1line, R.id.rockets, engStrList);
// adapter = ArrayAdapter.createFromResource(InfoActivity.this, android.R.layout.simple_spinner_item, R.array.engines);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
engineSpinner.setAdapter(adapter);
engineSpinner.setSelection(0);
Here is my xml spinner setup
<TableRow>
<TextView
android:text="#string/rocket"
android:padding="3dp"/>
<Spinner
android:id="#+id/rockets"
android:gravity="right"
android:entries="#array/engines"
android:clickable="true"
android:textColor="#color/colorblack"
android:spinnerMode="dropdown"
android:backgroundTint="#color/colorPrimary" />
</TableRow>
And finally, this is my string-array file I wanted to pull from (Do I put my string-array in it's own file in the values folder, or does it go inside the string file, I've seen both and don't know which, Thanks)
<?xml version="1.0" encoding="utf-8">
<resources>
<string-array name="engines">
<item>Ant</item>
<item>Dart</item>
<item>Dawn</item>
<item>Flea</item>
<item>Hammer</item>
<item>Kickback</item>
<item>MainSail</item>
<item>Mammoth</item>
<item>Nerv</item>
<item>Poodle</item>
<item>Puff</item>
<item>R.A.P.I.E.R</item>
<item>Reliant</item>
<item>Rhino</item>
<item>Skipper</item>
<item>Spark</item>
<item>Spider</item>
<item>Swivel</item>
<item>Terrier</item>
<item>Thud</item>
<item>Thumper</item>
<item>Twin Boar</item>
<item>Twitch</item>
<item>Vector</item>
</string-array>
</resources>
So to recap my questions, do I need to use ArrayList<String> or String[], how do I set up my ArrayAdapter, and where do I need to put my string-array?
Thank you in advance!
I recreate your sample and works fine for me changing
engStrList = engineNameList.toArray(new String[engineNameList.size()]);
adapter = new ArrayAdapter<String>(InfoActivity.this, android.R.layout.simple_spinner_item, engStrList);
to
engStrList = new String[]{"a","b","c"};
adapter = new ArrayAdapter<String>(InfoActivity.this, android.R.layout.simple_spinner_item, engStrList);
So my guess is that you should check what StagesData.getEngineNameList() is returning.
Also if you what to use your string array this is the right way
ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.engines));
Hope this helps

spinner with out "select option" but it should show blank

I am creating a spinner. The spinner shows the first row value as the default text.
I want the Spinner's text to be blank initially.
I could add a new empty row with list.add(" "); but I think that this approach looks ugly.
list.add("");//this make my ui ugly but with out this i can't make my spinner blank in starting.
list.add("1");//if i remove add("").then spinner take add("1") this should not happen
list.add("2");
How do I create a Spinner that initially doesn't display any text?
Update:
urineGlucoseSpinner = (Spinner) view.findViewById(R.id.spnner_urine_glucose);
ArrayList<String> ugList = new ArrayList<String>();
ugList.add("select");
ugList.add("1.5");
ugList.add("5.5");
ugList.add("0.8");
ugList.add("9.5");
ugList.add("12.0");
//ArrayAdapter<String> urineGlucoseAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, ugList);
ArrayAdapter<String> urineGlucoseAdapter = new ArrayAdapter<String>(getActivity(),R.layout.custom_spinner_text,ugList);
urineGlucoseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
urineGlucoseSpinner.setAdapter(urineGlucoseAdapter);
urineGlucoseSpinner.setOnItemSelectedListener(new OnUGItemSelected());
Write this code in oncreate method:
Spinner gender = (Spinner) findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.gender_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gender.setAdapter(adapter);
gender.setSelection(0);
and copy the below code and paste in string.xml
String.xml
<string-array name="gender_array">
<item> </item>
<item>Male</item>
<item>Female</item>
</string-array>
it will work properly.
You should include extra entry in adapter that represents "Select" or something , and make it the initial selected item in the Spinner.
OR may be you will have to create custom spinner or something which i am not sure of.
Take image look like dropdown and put them in background of textview.
Textview gender=(Textview)findViewById(R.id.gender)
gender.setText("");
gender.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder conductor = new AlertDialog.Builder(
Calculator.this);
conductor.setTitle("Select Gender");
int resId = getResources().getIdentifier("gender_array",
"array", getPackageName());
conductor.setItems(resId,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int index) {
int resId1 = getResources().getIdentifier(
"gender_array", "array",
getPackageName());
gender.setText(getResources()
.getStringArray(resId1)[index]);
}
});
AlertDialog alert = conductor.create();
alert.show();
}
});
String.xml
<string-array name="gender_array">
<item>Male</item>
<item>Female</item>
</string-array>

Set Value of spinner from Array in strings.xml

I have a spinner, that uses an array from strings.xml
if the array has 5 strings (1,2,3,4,5), and i want the spinner to show second
string (2) as default value, is this possible?
I know i can re-arrange the strings order so that first one is 2,
but this doesn't look very good if spinner dialog appears as (2,1,3,4,5).
Or does the array have to be created within my activity programatically
and then use setPostion()?
I have tried this, but get a fault when creating array in activity.
Can anyone please give me an example of how to create array and use
it in spinner()
I have also searched on here for answers but cant seem to find what i need.
Thanks for looking....
I recommend you check: http://developer.android.com/resources/tutorials/views/hello-spinner.html
You should create an ArrayAdapter in your Activity.
From the above link:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
You can use
spinner.setSelection(adapter.getPosition(value)));
to set the position.
Cheers for reply.....
Didn't do what i needed, but have managed to solve my problem as follows..
First i created an array within my activity, instead of strings.xml.
String[] NoCore_Array = new String [5];
{
NoCore_Array[0] = "1";
NoCore_Array[1] = "2";
NoCore_Array[2] = "3";
NoCore_Array[3] = "4";
NoCore_Array[4] = "5";
}
Then i created the spinner using...
Spinner spnNoCore = (Spinner) findViewById(R.id.spinner_nocore);
Then created the adapter, using above array....
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, NoCore_Array);
spnNoCore.setAdapter(NoCoreAdapter);
Then set default position of the adapter as follows...
//Set Default Selection
spnNoCore.setSelection(1);
Then rest of spinner code for actions...
spnNoCore.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//Get item from spinner and store in string conductorSize........
NoCore = parent.getItemAtPosition(pos).toString();
if (NoCore.equals(NoCore1)) { CoreNo = 1 ; }
if (NoCore.equals(NoCore2)) { CoreNo = 2 ; }
if (NoCore.equals(NoCore3)) { CoreNo = 3 ; }
if (NoCore.equals(NoCore4)) { CoreNo = 4 ; }
if (NoCore.equals(NoCore5)) { CoreNo = 5 ; }
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
Hope this may help other people who are having same problem with
setting default selection on Spinner.
However the layout of the dialog is not as good when done this way,
Radio buttons are missing, just looks like a text selection
with lines dividing the sections.

Combobox in Android

I need something like a combobox in access in android, i want to choose the customer per name, but in the background the id should be chosen. how to do?
In android comboboxes are called spinner. Nevertheless, gnugu has posted in his blog his own implementation of a combobox. http://www.gnugu.com/node/57
A simple example of an spinner would be the following.
First, edit your XML code with something like this
Spinner android:id="#+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Your java code should include something like this, the options are very intuitive. If you are using eclipse it will suggest you some options
public class SpinnerExample extends Activity {
private String array_spinner[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here come all the options that you wish to show depending on the
// size of the array.
array_spinner=new String[5];
array_spinner[0]="option 1";
array_spinner[1]="option 2";
array_spinner[2]="option 3";
array_spinner[3]="option 4";
array_spinner[4]="option 5";
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
}
}
An alternate solution to the need to link Customer ID to the selected Item.
To have a simple selector with text you cause make use of the array resources
Setup the Spinner in XML
<Spinner android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/colors"/>
If you need more data linked with the spinner you can use Objects to populate the spinner.
The default functionality of an ArrayAdapter is to call toString() on any object and pass that to the view.
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item.toString());
}
You can implement toString() in your object and it will display correctly in the spinner. Then to get the data back from the array you can add a handler onto ItemSelected and get the object back from the seed array or the ArrayAdapter.
ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, arrayOfObjects);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Log.d(arrayOfObjects[position]._id);
}
});

Categories

Resources