Android spinner location not updating - java

I have a spinner that populated with a string array. The spinner is populated when a button is pressed. the output is always game_0 even if I use the spinner and select say game_3. Is this because it's in a function?
public void game(View view) throws IOException {
myText="";
TextView myTextView= (TextView)findViewById(R.id.textView1);
String game_list[] = {"game_0","game_2","game_3","game_3","game_4","game_5"};
for(int i=0; i<game_list.length; i++){
myText = myText + game_list[i] +"\n";
}
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, game_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
String text = spinner.getSelectedItem().toString();
myTextView.setText("");
myTextView.append(text);
}

When are you calling your game(View v) method? There's no space for user action between the spinner initialization spinner.setAdapter(adapter); and the line that extract the selected value which is obviously (by default) the first of the array..."game_0".
You can use an OnItemSelectedListener to listen for user action on the spinner, or use a button with a click listener to check the spinner value upon submit.
Here's an example of a selected listener applied to a spinner:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// here get the selected value and do whatever you want
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// ignore this if you're not going to provide a "no-selection" option
}
});

Related

How do I populate a spinner inside spinner.setOnItemSelectedListener(...)?

As the title puts my query, I want to populate my spinner only when the user clicks it i.e., the spinner will initially be empty, when the user clicks it then and only then should all the items show. I tried out the following code:
if (spin1 != null) {
spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ArrayList<String> arr=new ArrayList<String>();
arr.add("Hello");
arr.add("Hey");
arr.add("Yo");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item,arr);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
assert spin1 != null;
spin1.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
}
But my above code is not working. The spinner is empty when I click on it. Can you please tell me why and how to fix this issue?
You can register TouchListener to set Adapter for the Spinner on the first click like in the code snippet shown below:
// array list to populate the spinner's item
List < String > array = new ArrayList < > ();
array.add("Nepal");
array.add("India");
array.add("China");
// create adapter instance from the array list
ArrayAdapter < String > adapter = new ArrayAdapter < > (requireContext(),
android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// register on item selected listener as usual
binding.testSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView << ? > parent, View view, int position, long id) {
Toast.makeText(requireContext(), array.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView << ? > parent) {}
});
// set on touch listener as we cant set onclick listener in spinner
// because it is made to throw exception
binding.testSpinner.setOnTouchListener((v, event) - > {
// set the adapter in the touch event
// ACTION_UP occurs when user releases the finger
if (event.getAction() == MotionEvent.ACTION_UP) {
binding.testSpinner.setAdapter(adapter);
}
// return false as we dont want to consume the event
// but want to allow it to propagate in the parent view hierarchy
return false;
});

how I can hide the element with index 0 from dropdown list in spinner

Please tell me how can I hide the item at index 0 from the dropdown in the spinner in Android Studio? I am using this code, it works, but when I open the list, it shows at the bottom. That is, it is focused on the elements below. what do i need to change?
SpinnerName = (Spinner) v.findViewById(R.id.spinner1);
ArrayList<String> names = new ArrayList<>();
names.add(0, "SELECT");
names.add(1, "Name1");
names.add(2, "Name2");
final int listsize = names.size()-1;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names){
#Override
public int getCount() {
return(listsize);
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerName.setAdapter(adapter);
adapter.setDropDownViewResource(R.layout.spinner_list);
SpinnerName.setSelection(listsize);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
....
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
SpinnerName.setSelection(listsize);
your problem is here! you are passing the total list size number and
that where you are doing wrong, because setSelection method use to
show default index of spinner.
you can simply do that SpinnerName.setSelection(1); that would give you the fist spinner item unless showing the names.add(0, "SELECT"); item

how to get the items changed in spinner android studio

I want to change the value of the second spinner when the value of the first spinner is changed I tried the solutions but did not get an exact solution so anyone have a solution for that so please suggest or any question then please ask
ArrayAdapter<String> deptArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Province));
deptArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProvinceEyeTest.setAdapter(deptArrayAdapter);
deptArrayAdapter.notifyDataSetChanged();
Set a OnItemSelectedListener() first.
spinnerProvinceEyeTest.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString(); //this is your selected item
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
In onItemSelected() of above Listener, place your condition and set resource for second Spinner as:
If(selectedItem == "YourText"){
//Here, you're initalizing the second `Spinner`
ArrayAdapter<String> secondArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.YourList));
secondArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
secondSpinner.setAdapter(secondArrayAdapter);
}
else{
//Use any other list with arrayAdapter in case of other item selected.
//Use can use If-else-if or Switch to select different resource for different item of first spinner
}
Reference - Official Documentations.

Android Spinner Doesn't Return Id Properly

I'm having a difficulty in spinner android, more specifically in the data saving part.
First, I'm going to tell you what is the purpose behind the code below.
I want to create a spinner that user can choose which planet to buy, then when he/she hits the submit button, a toast will appear saying "You wanted to buy: ...." then followed by a purchase summary like username & price.
However, in the middle of the process I'm having a hard time to save the id of each spinner's element.
Every time I chose "Earth" (id= 1) & hit submit, the toast will always refer back to "Mars" which has id = 0. So it seems that the problem is my submit button will always reset the chosen id.
I intentionally set planetSpinner() method to return int, thus I could always track down the "id" being returned. But again, the submit button would always make it shows to id = 0.
Can anyone help me? I would really appreciate that. Thank you.
Spinner Code (MainActivity.java)
public int planetSpinner(){
context = this;
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
cSpinner = (Spinner) findViewById(R.id.coffee_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cSpinner.setAdapter(dataAdapter);
cSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You selected: " + cSpinner.getItemAtPosition(position), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_LONG).show();
}
});
return cSpinner.getSelectedItemPosition();
}
Submit Purchase Code (MainActivity.java)
public void submitOrder(View view){
Toast.makeText(MainActivity.this, "You wanted to buy: " + planetSpinner(), Toast.LENGTH_LONG).show();
displayMessage(confirmationOrder(userName, price));
}
public class MySpinner extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.coffee_spinner);
spinner.setOnItemSelectedListener(this);
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Have you try this:
Toast.makeText(MainActivity.this, "You selected: " + categories.get(position), Toast.LENGTH_LONG).show();
It is because the spinner was reinitialized everytime you call the function. Thus, the selected value was the first item, that is why your function always returns 0. Hope that helps.

how to change the string array of a spinner at runtimeHow to use the selected item of a spinner in an if statement (Android in eclipse)

Hi I have a spinner (spinner1) and when the user selects an item from it (example: "Canada" I want the spinner2 to populate with Provinces of "canada". I have tried the following but it doesnt work. I tried to do this by using:
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List list = new ArrayList();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
for some reason the items aren't being added to spinner2. please help
This code
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
will only run the first time the Activity is created since it is in your onCreate(). You need to add this code to your onItemSelected() for spinner1. So you first need to implement an OnItemSelected listener to that spinner.
spinner1.setOnItemSelected(new OnItemSelected()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id)
{
TextView tv = (TextView)v; // cast the View to a TextView
if ("Canada".equals(tv.getText().toString())
{
addItemsOnSpinner2();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Something like this should work. Although, you will probably be safer to use position instead of getting the text.
OnItemSelected Docs

Categories

Resources