Dynamic Spinners in Android (General Workflow Question) - java

Like this one, I've seen a few how-to's on this site, but truthfully, I'm not really getting it.
I want one spinner's content to be based upon a previous spinner selection, like in a States and Cities scenario. In general terms, what is the workflow? Are the results of the second spinner filtered based on the first spinner, or is the second spinner pointing to a completely different list based on the first spinner?
For my own simple learning project, I've built several string-arrays in the strings.xml (AL-Cities, AK-Cities, AR-Cities, etc). I'd like the city spinner to populate from the correct array based on a choice from the state spinner. But I'm wondering if instead I should just have one large multidimensional array of "Cities" that have a state abbreviation as an additional identifier, and then point the second spinner at that using the state abbreviation as a filter. It would seem like the former would provide better performance.
Any help (and code examples) would be greatly appreciated. I'm not new to programming (php mostly, so I guess scripting is more accurate), but I am new to java. My code so far with the spinners not linked is below with the second spinner pointing to an undifferentiated city_array.
Thank you!
public class Example1 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example1);
Spinner spinState = (Spinner) findViewById(R.id.spin_state);
ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(
this, R.array.state_array, android.R.layout.simple_spinner_item);
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinState.setAdapter(adapter3);
Spinner spinCity = (Spinner) findViewById(R.id.spin_city);
ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(
this, R.array.city_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCity.setAdapter(adapter4);
}
}

You could try and get the position from your first spinner, the one you've selected and then populate your second spinner after retrieving the proper array based on that position.
You have to listen for your first adapter being changed:
spinner. setOnItemSelectedListener(new MyOnItemSelectedListener());
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String choice = parent.getItemAtPosition(pos).toString();
populateSecondSpinnerMethod(choice)
}
}
public void onNothingSelected(AdapterView parent) { // Do nothing.
}
}

Related

Get spinner selected item and passing data

What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.
UPDATE:
I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.
So this is my code for 1st activity, I will just put only one first :
btnAsia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("continent", "asia");
startActivity(intent);
}
});
This is the string array in strings.xml:
<string-array name="asia">
<item>Japan</item>
<item>Thailand</item>
<item>Vietnam</item>
<item>South Korea</item>
</string-array>
and this is the code in 2nd activity:
private void DestinationSpinner()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String continent = bundle.getString("continent");
switch (continent) {
case "asia":
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
break; }
and lastly this is the code for retrieve selected item from spinner:
public void AvailableAirlines()
{
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected=spinnerDestination.getItemAtPosition(position).toString();
if (continent.equals("asia") && selected.equals("Japan"))
{
availableAirlines.setText("Available airports");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.
I think the issue is this line if(selected=="Japan")
In Java you will need to use equals instead of the == operator.
The == checks if the two pointers are pointing to the same memory location.
Equals will compare their content.

Generate Plain Text Fields Based on Chosen Spinner Value?

I'm currently working on creating an app in android studio. The problem I am facing is generating a number of "plain text" objects based on the number chosen in a spinner. I have included layout of the activity below.
layout of activity can be seen here
Once the "number of people" are picked, then the area to enter the peoples names will be generated based on that. Max number of people will be 4.
Any help on how to do this would be much appreciated!
I would suggest using an OnItemSelectedListener() on your spinner along with setting the setVisibility() of your 'person' fields.
This code will assume your minimum people to be 1. Each time a new value is selected from the spinner the fields will appear or disappear. Using GONE for visibility will hide the field but also remove the space used by it. Use INVISIBLE if you want to keep the space.
Also don't bother setting the visibility in the xml layout code as this can cause issues.
person1 = (EditText)findViewById(R.id.person1);
person2 = (EditText)findViewById(R.id.person2);
person3 = (EditText)findViewById(R.id.person3);
person4 = (EditText)findViewById(R.id.person4);
list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
spinnerValue = parent.getItemAtPosition(position).toString();
int value = Integer.parseInt(spinnerValue);
// Simpler logic for the visibility of the 'people' - kudos to RobCo for pointing this out//
person1.setVisibility(value>=1? view.VISIBLE:View.GONE);
person2.setVisibility(value>=2? view.VISIBLE:View.GONE);
person3.setVisibility(value>=3? view.VISIBLE:View.GONE);
person4.setVisibility(value>=4? view.VISIBLE:View.GONE);
/*
if (value == 1)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.GONE);
person3.setVisibility(View.GONE);
person4.setVisibility(View.GONE);
}
else if (value == 2)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.GONE);
person4.setVisibility(View.GONE);
}
else if (value == 3)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.VISIBLE);
person4.setVisibility(View.GONE);
}
else
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.VISIBLE);
person4.setVisibility(View.VISIBLE);
}
*/
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
Good luck.
You simply do it by setting the visibility of all the 4 EditTexts as false and set a listener to the spinner. And inside the listener add if else statement and depending upon the selection you can set the visibility on for the EditText fields.

using spinner in android development

I'm new to android development, I have some experiences on C# windows programming, but also very little. I'm working on an android application which uses spinners. So far, I found a tutorial which make spinner items, and displays spinner text in text view, as you select spinner item. The code lookes like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner =(Spinner)findViewById(R.id.sp);
text=(TextView)findViewById(R.id.tv);
ArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource(this, R.array.spinnerarray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new function());
}
public class function implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long id) {
// TODO Auto-generated method stub
String str=parent.getItemAtPosition(pos).toString();
text.setText(str);
}
I want to make an application, which will calculate some points, with the grade user would choose. Example: spinner will contain grades, such as Negative(1), Positive(2),Good(3), Very Good(4), Excellent(5). I want to achieve, that when an user chooses one grade, lets say very good, that the application will use the grade for very good which is 4, and it would transform it to some points, determined by me ( 1=20, 2=40,3=60,4=80,5=100). The points will be later used in calculation, but I have no idea how to assign points to certain grade. I hope you understand my question and thank you for your help.
I had the same app for windows, there I just used something like: if(veryGood.IsSelected==true){points = 20}, and i want to achieve same effect here.
You need a simple modifications on your function class:
public class function implements OnItemSelectedListener {
private final static int[] grades = new int[]{20,40,60,80,100}; //change in whatever you want. The length of the array must be the same of the adapter, or an ArrayIndexOutOfBoundException may be throwed.
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long id) {
text.setText(grades[pos] + " points!");
}
}
PS: in Java is a good practice to use upper case initial on class names e.g. Function instead of function.

Automated Spinner Selection in android

I am developing an android which has 4 spinners(A,B,C,D).
What I want to achieve is
If Spinner A is set to a value I want the remaining spinners to automatically change their value depending on the value of A
Like if I set Movie(in A)--->Ticket(in B)---->Place(in C)---->Time(D) to automatically fill in.
Thanking you
ChinniKrishna Kothapalli
I think you can set an OnItemSelectedListener to your Movie Spinner. The Spinner tutorial is an adequate example. Your OnItemSelectedListener may be like this:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if (parent.getItemAtPosition(pos).toString().equals("firstMovieName")) {
// set spinner B/C/D with the corresponding information of first movie
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
The onItemSelected method above may be too simple for your need. You need figure it out how to link the four spinners yourself, but May it helps :)

I need help with my first Spinner!! Not Displaying values

This is the first time I am trying to use a spinner and I need some help.. I made a layout with a spinner object on it and then I also made a array.xml with the numbers that I would like in the spinner in it. I run the following code and the screen displays without any values in my spinner??
public class SpinnerExaple extends Activity {
private Spinner numbersSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.numbersSpinner = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<String> numbersArray =
new ArrayAdapter<String>(this, R.layout.main,
getResources().
getStringArray(R.array.numbers));
}
}
You got the reference to the spinner, you got your AdapterArray set correctly- but you didn't attach the adapter to your spinner.
Add the line:
numbersSpinner.setAdapter( numbersArray );
You never set your numbers array into the spinner. Try adding the following at the end of the method:
numbersSpinner.setAdapter(numbersArray);
Also check out the hello-spinner tutorial.

Categories

Resources