How to let user choose a specific year from a spinner - android

Hello I want the user to be able to click a spinner and choose a year from those I provide. I would provide a range from 1970 to current year, but I don't know how to implement it.
If I create a spinner and give it an array like this
<string-array name="spinnerItems">
<item>1970</item>
<item>1971</item>
</string-array>
Then I would need to add more than 40 items by hand, and I would need to update the app manually every year. Also the spinner onClick callback returns not the string value but the index of the string in the array, so for example 1972 would be index 3.
Also I will provide another spinner where the user will choose a year that's greater or equal of the year choosen in the first spinner.
In the end I want tos end an api request with an interval of years.
How can I do this?

I think you have to create year picker instead of creating number list of spinner
Try this
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = 1900; i <= thisYear; i++) {
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, years);
Spinner spinYear = (Spinner)findViewById(R.id.yearspin);
spinYear.setAdapter(adapter);
Hope this will help..

You can add items to a spinner programmatically.
You can find out with a simple command which year we have right now and can froce the program to add numbers from e.g. 1800 to the current year to your spinner.
WARNING: Pseudo code
Spinner mySpinner = (Spinner) findViewById(R.id.spinner);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
ArrayAdapter<String> adapter;
List<String> list;
list = new ArrayList<String>();
for(int i = 1800; i <= year; i++)
{
list.add(i);
}
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);

Related

How to add a default selected value in android dropdown

I have a dropdown which takes its values from a database, I then want to add a default value to the existing drop down values. In this case the default value would be the selected value.
StringBuilder strbuilder = new StringBuilder();
ArrayList<String> arr_list = new ArrayList<String>();
List<String> m = new ArrayList<String>();
//This get the data values from database
m = db.getData();
int ms = m.size();
String str = strbuilder.toString();
String[] str1 = str.split(",");
try {
if (ms > 1) {
//This is my default value
m.add("Default Value");
for (int i = 0; i < ms; i++) {
m.get(0);
}
} else {
m.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, m);
dropdown.setAdapter(adapter);
The codes above is able to add the values from the database to the dropdown and the Default Value is added but it doesn't appear to be the selected value.
For instance if the values from the database are "Apple, Mango,Pineapple" and the default value is "ALL FRUITS".
EXPECTED DROPDOWN
ALL FRUITS
Apple
Mango
Pineapple
Please how can I do make the default value the selected value? Thanks in advance.
I think you need below code.
List<String> categories = new ArrayList<String>();
categories = db.getData();
categories.add(0,"your_default_value");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setSelection(0);
Remember when you want to add any value to the very first of Arraylist you just do
arraylist.add(0,"value");
This will add the value to the very first index of arraylist and push all other element down.
In case you need any other element to be selected not first one
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
int i=categories.indexOf("Education");
spinner.setSelection(i);
If the default value is always going to be at the 0 index, just get a reference to your dropdown/spinner, then set:
spinner.setSelection(0);
And here is a previously answered question detailing how to set it by value, if you'd rather do that.
https://stackoverflow.com/a/4228121/3299157

Populating a spinner with specific entries from an array

I am working on an application for Android. For this I am making an Activity in which you select your country and then a spot in that country. I have one spinner that contains a list of all available countries. Now, what I want it to do is get the country that has been selected, then filter a list of spots that I have for the items that start with the country that has been selected. Then it should put the spots for the selected country into a different spinner. Just for clarity, the list of countries is just a list of countries, and the list of spots looks like:
Country1 - Spot1
Country1 - Spot2
Country2 - Spot1
Country2 - Spot2
And so on.
This is what I thought the code should work like:
Get selected country from spinner 1.
Make a new ArrayList containing the spots.
Make a second empty ArrayList.
For each entry of the ArrayList containing the spots, check if it starts with the selected country.
If so, add it to the second ArrayList.
Once this is all done, make an ArrayAdapter with the second ArrayList.
Set this ArrayAdapter for spinner 2.
I tried to achieve this with the following code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
ArrayList<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(R.array.spots_array);
ArrayList<CharSequence> arraylist2 = new ArrayList<CharSequence>();
for (i=0; i<arraylist.size(); i++) {
String delimiter = " - ";
if ((arraylist(i).split(delimiter)).equals(selectedCountry)) {
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, arraylist2<CharSequence>, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
But it gives several errors:
At addAll() it says: "The method addAll(int, Collection) in the type ArrayList is not applicable for the arguments (int)"
At arraylist it says: "The method arraylist(int) is undefined for the type Configuration"
At string (inside substring) it says: "string cannot be resolved"
I am still relatively new to Android, and am having a lot of trouble getting this working. Can anybody please help me out?
There is a lot of little mistakes in your code :
To access an element in an arraylist use the get(position) method
When you add your "spot_array", you actually add the id of the resource, not the array itself (see here)
Here is your code updated, it should works or may need some tweaks
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
List<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(Arrays.asList(getResources().getTextArray(R.array.spots_array)));
List<CharSequence> arraylist2 = new ArrayList<CharSequence>();
String delimiter = " - ";
for (int i=0; i<arraylist.size(); i++) {
String country = arraylist.get(i).toString();
if (country.contains(selectedCountry)) {
arraylist2.add(country.substring(country.lastIndexOf('-') + 2));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, android.R.id.text1, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
You have several errors in your code.
Firstly, the method addAll of the ArrayList must take as an argument a Collection. You are passing an Android array id R.array.spots_array; bear in mind that the Android ids are integers.
The usually method to fetch a string array from Android resources is (inside an activity):
String[] myArray = getResources().getStringArray(R.array.spots_array);
Second error: you should access the ArrayList elements by calling the method get(position) , not directly (arraylist(position)). Something like arraylist.get(position).
Third error:
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
should simply be arraylist2.add(arraylist.get(i)); for adding one list element to another.
More on ArrayLists can be found here.

Using Multiple Spinners, But Only One Spinner Has All The Data

I have two spinners and two arrays. However, one spinner receives both arrays while the other receives no values from either of the two arrays. Note: I do not want to use radio buttons as the data is shortened for review.
final ArrayList<String> serialnums = new ArrayList<String>();
serialnums.add("576798");
serialnums.add("495874");
serialnums.add("345667");
serialnums.add("956345");
final ArrayList<String> carrys = new ArrayList<String>();
serialnums.add("R");
serialnums.add("L");
serialnums.add("F");
serialnums.add("B");
s1 = (Spinner) findViewById(R.id.spinnerSerial);
spinnerCarry = (Spinner) findViewById(R.id.spinnerCarry);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, serialnums );
ArrayAdapter<String> adapterCarrys = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, carrys );
s1.setAdapter(adapter);
spinnerCarry.setAdapter(adapterCarrys);
Note 2: Spinner s1 gets all the data
One spinner has all the data because you are assigning all the data to it. Change this:
final ArrayList<String> carrys = new ArrayList<String>();
serialnums.add("R");
serialnums.add("L");
serialnums.add("F");
serialnums.add("B");
to this:
final ArrayList<String> carrys = new ArrayList<String>();
carrys.add("R");
carrys.add("L");
carrys.add("F");
carrys.add("B");
You are adding "R" "L" "F" "B" to serialnums add it to carrys

sort array list from second item android

i have a array list for using it in spinner ,i have first value i spinner as title and i want to sort array list from second item in the spinner but i dont know how to do this i am using below trick but it sort whole array list including first item which is title so how to statr sorting from second item...
my code is below...
// this is my title ie. "provincia"
String select2= "Provincia";
if(!estado1.contains(select2)){
estado1.add(select2);
}
for (int i = 0; i < sitesList1.getEstado().size(); i++)
{
if(!estado1.contains(sitesList1.getEstado().get(i)))
{
estado1.add(sitesList1.getEstado().get(i));
Collections.sort(estado1);
}
use below code for show it in spinner...
final ArrayList<String> estado1 = MainMenu.barrio1;
final Spinner estado11 = (Spinner) findViewById(R.id.Spinner04);
ArrayAdapter<String> adapterbarrio = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, estado1)
estado11.setAdapter(adapterbarrio);
Why not remove the title / only add the title after the list has been sorted?
How about this
List<String> list = new ArrayList<String>();
// Fill list
String title = list.get(0);
list.remove(0);
Collections.sort(list);
list.add(0, title);
One way would be to split the arraylist like
estado1.subList(1,estado1.size()-1);
This would return a sublist excluding your title.
Use bubble sort! and start at index = 1!
final ArrayList<String> estado1;
for(int i=1; i<estado1.size() ; i++) {
for(int c=i; c<estado.size() ; c++) {
if(estado1.get(i).compareTo(estado1.get(c)))
{
String temp = estado1.get(i);
estado1.remove(i);
estado1.add(i, estado1.get(c));
estado1.remove(c);
estado1.add(c, temp);
}
}
}
PS: very bad performance

Android spinner prompt text not showing [duplicate]

This question already has answers here:
How to make an Android Spinner with initial text "Select One"?
(36 answers)
Closed 9 years ago.
The first year from the data array is shown instead of the text from prompt in my spinner. I tried adding the prompt in XML, but I also tried from code. Furthermore, it gives me a "resource not found error", when adding the spinnerSelector attribute.
XML
<Spinner
android:id="#+id/spinnerYear"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:drawSelectorOnTop="true"
android:padding="5dip"
android:prompt="#string/spinner_header"
android:background="#drawable/selector_yearspinnerback"
android:layout_below="#+id/linearLayout_gender_btns"
android:layout_centerHorizontal="true"></Spinner>
-- android:spinnerSelector="#drawable/category_arrow"
Code
ArrayList<String> yearList = new ArrayList<String>();
int now = new Date().getYear() + 1900;
for (int i = now; i > now - 110; i--) {
yearList.add(i + "");
}
Spinner spinner = (Spinner) findViewById(R.id.spinnerYear);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yearList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Perhaps you are seeing the spinner drop down items as list without any prompt text. There are two modes in which spinner shows the items, dropdown and dialog.
Add this attribute to your spinner as an XML atrtribute:
android:spinnerMode="dialog"
And you will now get items in a popup dialog select list instead of drop down list.
You have to set adapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item); after
spinner.setAdapter(adapter);
So the fixed code would be:
ArrayList<String> yearList = new ArrayList<String>();
int now = new Date().getYear() + 1900;
for (int i = now; i > now - 110; i--) {
yearList.add(i + "");
}
Spinner spinner = (Spinner) findViewById(R.id.spinnerYear);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yearList);
spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
(I hope it works for you like it works for me :D!)
For me, both android:prompt XML attibute as well as Spinner.setPrompt work, and list selector displays correct title.
Try to find bug in your code, or make call to Spinner.getPrompt at some point and print this to log, to find our from where you get invalid title.

Categories

Resources