Set Value of spinner from Array in strings.xml - android

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.

Related

do a task based on multiple onItemSelectedListeners

i am using three spinners to get input from the user, and based on this information i will then graph some data. however i cannot seem to figure out how to do this. i have the following code (extract to show the important bits):
final GraphView graph = (GraphView) findViewById(R.id.graph);
Spinner selectGraphSpinner = (Spinner) findViewById(R.id.graphSpinner);
Spinner selectUserSpinner = (Spinner) findViewById(R.id.userSpinner);
Spinner selectTimeSpinner = (Spinner) findViewById(R.id.timeSpinner);
String[] items = new String[]{"Please Select a User", "04950f4ae53f80", "another user"};
// Create ArrayAdapters for Spinners
ArrayAdapter<CharSequence> selectGraphAdapter = ArrayAdapter
.createFromResource(this, R.array.Graphs,
android.R.layout.simple_spinner_item);
ArrayAdapter<String> userSpinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
ArrayAdapter<CharSequence> spinTimeAdapter = ArrayAdapter
.createFromResource(this, R.array.TimeIncrements,
android.R.layout.simple_spinner_item);
selectGraphSpinner.setAdapter(selectGraphAdapter);
selectUserSpinner.setAdapter(userSpinnerAdapter);
selectTimeSpinner.setAdapter(spinTimeAdapter);
the onItemSelectedListeners x 3 repeat for other spinner:
selectUserSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
itemOne = parent.getItemAtPosition(0).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
the graphing logic so far:
while (itemOne != null) {
if (itemOne.equalsIgnoreCase("04950f4ae53f80")) {
if (itemTwo.equalsIgnoreCase("Estimated vs Actual Time")) {
if (itemThree.equalsIgnoreCase("Day")) {
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(getData(Data, "Day"));
graph.addSeries(series);
} else {
}
} else {
}
} else {
}
}
i know that the graph works as i tried with one spinner, but cant figure out why the listeners are not saving the variables (which i declared global - static String itemOne, etc)
thanks
edit: the spinners contain multiple strings with a different initial one, but the used ones are mentioned,
I managed to do this by saving the clicked items from each spinner to a global function/variable. this then allowed me to run a logic check which would return true or false depending on the case. i then put the graphing method within the listeners such that it would be implemented if the logic check returned true

Sorting the values in Spinner depending on the condition

I want to make two spinners, the first spinner have the list of states and second spinner contains the list of cities . If i select the particular state from the first spinner then next spinner must show only the cities on the selected state only .
My android code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner state = (Spinner) findViewById(R.id.spinnerState);
ArrayAdapter<CharSequence> stateadapter = ArrayAdapter.createFromResource(
this, R.array.item_state, android.R.layout.simple_spinner_item);
stateadapter.setDropDownViewResource(R.layout.spinner_layout);
state.setAdapter(stateadapter);
Spinner city = (Spinner) findViewById(R.id.spinnerCity);
ArrayAdapter<CharSequence> cityadapter = ArrayAdapter.createFromResource(
this, R.array.item_city, android.R.layout.simple_spinner_item);
cityadapter.setDropDownViewResource(R.layout.spinner_layout);
city.setAdapter(cityadapter);
}}
I have created all my for the state and cities.
There are lots of ways you can achieve this, for example:
ArrayAdapter<CharSequence> stateadapter;
switch(state)
{
case "Florida":
{
stateadapter = ArrayAdapter.createFromResource(this, R.array.cities_florida, android.R.layout.simple_spinner_item);
} break;
}
(kinda hardcoded)
The most optimal solution is to define it on an xml file (maybe you can get this somewhere on the internet) and write a class that reads the file and return all the cities on the selected state.
read:
https://developer.android.com/training/basics/network-ops/xml.html
Add a listener to the Spinner state
state.setOnItemSelectedListener(this);
Implement the listener:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedState = state.getSelectedItem().toString();
List<String> citiesInState = new ArrayList<>();
// add all cities in selectedState to this list using citiesInState.add();
// this will depend upon how you are storing the cities and states
ArrayAdapter<String> cityDataAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, citiesInState);
cityDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
city.setAdapter(cityDataAdapter);
}

Spinner, not set value if i dont click(android)

I have a spinner:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int childposition, long id) {
textView.setText(spinner.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText("");
}
});
Above you'll see that textView - is my text object. I'm displaying a text item spinner in the textView when I click it. If I dont click the spinner then my textView must be textView.setText("");
But the spinner is always set text in my textView, even if I do not choose spinner.
Question
How can I accomplish this?:
If I dont choose item spinner, textView is empty: textView.setText("");
If I do choose the item spinner, textView gets: textView.setText(spinner.getSelectedItem().toString());
String item = parent.getItemAtPosition(childposition).toString(); //Get selected item
if(item.equals("spinner")){ // Check if it equals spinner
textView.setText(item); // Set text to item
}else{
textView.setText(""); // If it doesn't equal spinner set text to ""
}
If I understood the question right, putting this instead of textView.setText(spinner.getSelectedItem().toString()); and deleting content of onNothingSelected should do the trick.
UPDATE
I finally understood what you mean. To do this create your spinner like this and add "" as first choice in your string-array resource :
String[] newArray = getResources().getStringArray(R.array.yourArray);
List<String> myResArrayList = Arrays.asList(newArray);
ArrayList<String> spinnerItems = new ArrayList<String>(myResArrayList);
//Making adapter with ArrayList instead of String[] allows us to add/remove items later in the code
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerItems);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinnerItems.remove(0);
adapter.notifyDataSetChanged(); // Here we remove the first choice which is "" so the user won't be able to select empty.

Android How to retrieve value of Dynamically added Spinner

I am dynamically adding the Spinners in my application by parsing the XML file.
I have done using the below code
List<Spinner> allspin = new ArrayList<Spinner>();
Spinner spin = new Spinner(getParent());
allspin.add(spin);
spin.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getParent(),
android.R.layout.simple_spinner_item, selectval);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
Spinners are displayed correctly but i don't know how to retrieve the value of selected spinner. If there is one spinner i can retieve, but there are multiple how should i do?
You can get the reference of the spinner from your arraylist like this :
Spinner spn = allspin.get(index);
After that you can get the selected item by simply calling:
spn.getSelectedItemPosition();
You can set id of spinner dynamically.
For that,you can use
spin.setId(i); //if you use i of for loop for creating multipal spin at a tym or you can use a global variable i,incremented by one each time you create a spinner
and further,you can use those ids to get values from particular spinner.
Example:
for(int i=1;i<4;i++)
{
Spinner spin=new Spinner(getApplicationCotext());
spin.setId(i);
...
//other code
...
mLayout.add(spin);//add this spinner to your layout(mLayout is object of your layout in xml)
}
Now,
for(int i=1;i<4;i++)
{
Spinner sp=(Spinner)findViewById(i);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
System.out.println(sp.getText().toString());//prints values of a pinner when it is changed/selected
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
If you need multiple spinners (I'm not sure I understand your use case), then, as you're creating each of them, you need to also create the appropriate listeners. You shouldn't have to retrieve values of spinners yourself; handling these selection events should be done in your listeners. Perhaps if you explained what you're attempting to do a bit better it would be easier to help...

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