How to save the spinner selected value in android? - android

I am trying to save spinner selected value, but i am getting like below i shown when i retrieve the details. Anybody know what is the problem.
Spinner:android.widget.Spinner#43e807a0

Have you used the getSelectedItem() inside setOnSelectedListner? If not, do as shown below:
mPres_doctor.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter, View view,
int position, long id) {
String pres_doctor = mPres_doctor.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});

The result is displaying as an object value, usually I follow the below method to get the spinner values:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.spinner, android.R.layout.spinner_layout);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
strings.xml
<string-array name="spinner">
<item>Dev</item>
<item>Stieve</item>
<item>John</item>
<item>Britto</item>
</string-array>

Related

My spinner does not display the selected item and doesn't call onItemSelected

I have an android spinner that allows the user to select a translation. I can tap the spinner and it will reveal a list with available translations, but when I select an item in the list it will not appear in the spinner and neither does the onItemSelected method get called.
Here is the xml code for the spinner:
<Spinner
android:id="#+id/trans_list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/chap_list"
android:layout_weight="1" />
Here is the relevant code for initiating the spinner. (edit) This code is ran from inside a Fragment class and not from my MainActivity class:
trans_spinner = v.findViewById(R.id.trans_list);
ArrayAdapter<String> adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_spinner_dropdown_item, translations);
trans_spinner.setAdapter(adapter);
trans_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String translation = trans_spinner.getItemAtPosition(trans_spinner.getSelectedItemPosition()).toString();
Log.d("trans", translation);
Toast.makeText(view.getContext(), translation, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("test", "1");
}
});
trans_spinner.setSelection(1);
Neither the onItemSelected() or onNothingSelected() method gets called when I select an item. I found this page describing an issue very similar to mine:
Android Spinner will not launch OnItemSelected and current selected item is not displayed in Spinner
However the user did not present a clear solution to their problem so it doesn't help me much.
I am not sure if it is relevant, but the items in the spinner are taken from an online webpage that provides JSON data to fill the spinner. This seems to work, as the options do appear in the spinner list. The issue is that upon selecting one of them, the spinner appears empty and the listener doesn't do anything.
So I found out that the issue was actually because of how I obtained the list of strings to put inside the spinner. As mentioned in the original post, I am loading the string values from a webpage in JSON format. I'm using the Retrofit2 API for this.
The problem was caused by the fact that I was downloading this data and then initializing the spinner both in the onCreateView() method of my fragment. What I did to fix it is I created a new method that initializes the spinner, and then I would call it from the onResponse() method used by the Retrofit API. This means that it doesn't initialize the spinner until after it has finished downloading/populating the list of strings.
<Spinner
android:id="#+id/planets_spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
f the available choices for your spinner are pre-determined, you can provide them with a string array defined in a string resource file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
With an array such as this one, you can use the following code in your Activity or Fragment to supply the spinner with the array using an instance of ArrayAdapter:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
// 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);
When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event.
To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method. For example, here's an implementation of the interface in an Activity:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
The AdapterView.OnItemSelectedListener requires the onItemSelected() and onNothingSelected() callback methods.
Then you need to specify the interface implementation by calling setOnItemSelectedListener():
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
If you implement the AdapterView.OnItemSelectedListener interface with your Activity or Fragment (such as in the example above), you can pass this as the interface instance.
Java Code
public class MainActivity extends AppCompatActivity {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
List<String> translations = new ArrayList<>();
translations.add("string1");
translations.add("string2");
translations.add("string3");
translations.add("string4");
translations.add("string5");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, translations);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object getPosition = parent.getItemAtPosition(position);
String value = getPosition.toString();
Toast.makeText(getActivity(), value, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
XML Code
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner">
</Spinner>
Add this code after init adapter
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
And to get the selected item inside onItemSelected
translations.get(position)

When I click on a Spinner item, it will show a ListView

I want to make an app which contains a Spinner and a ListView and when I click a Sinner item it will open a new ListView, no new Activity just to update the ListView from the database.
For instance, I have Europe and Africa in the Spinner and when I click Europe it will show me a ListView with the European countries, when I click Africa it will show me a ListView with the African countries.
I searched this on the internet, but I could not find anything.
First of all, to set up a spinner you need an adapter. Then you need to use an OnItemSelectedListener. Use this code:
europeListView = (ListView) findViewById(R.id.europeListView);
africaListView = (ListView) findViewById(R.id.africaListView);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.countries, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(adapter.getItem(i) == "Europe"){
europeListView.setVisibility(View.VISIBLE);
africaListView.setVisibility(View.INVISIBLE);
} else if(adapter.getItem(i) == "Africa"){
africaListView.setVisibility(View.VISIBLE);
europeListView.setVisibility(View.INVISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Finally, make a string array called "countries" containing Europe and Africa in your strings.xml file like so:
<string-array name="countries">
<item>Europe</item>
<item>Africa</item>
</string-array>
Hope this helps!

How to review the selected item on spinner

Here is my code for my spinner.. i want it to save to my database by using setText but theres no option for setting it into setText.. this is how i want it to save on my database spinpstat.setText(student.status);
this is how i want it to declare in my onClick(View view)
student.status = spinpstat.getText.toString(); but it gives me following error
spinpstat = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapterstat = ArrayAdapter.createFromResource(this, R.array.statuslist, android.R.layout.simple_spinner_item);
adapterstat.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinpstat.setAdapter(adapterstat);
spinpstat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
projstat = spinpstat.getSelectedItem().toString();
spinpstat.setSelection(position);
parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
this is the data i saved .. i set the spinner status in old student
but this how the data result in review of the data i saved.. my spinner instead of status is old student it set as new student which is the first value in my spinner list
any help will do.. thanks in advance..
Use Spinner.setSelection to set selected item from Spinner like:
spinpstat.setSelection(adapterstat.getPosition(student.status));
And get selected item from Spinner on onClick as:
student.status = spinpstat.getSelectedItem().toString();

Returning a String from ArrayAdapter

I have created a Spinner and ArrayAdapter as follows:
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.units_array1, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
The units_array1 is a string array declared in a xml file like this:
<string-array name="units_array1">
<item>Centimeters</item>
<item>Meters</item>
<item>Kilometers</item>
<item>Inches</item>
<item>Foots</item>
<item>Miles</item>
</string-array>
Now I want to implement some If-ELSE conditions that are based on the elements in string-array. I Have researched a lot on the internet for this but haven't found out any solution that works. Please help me in implementing a function that returns the individual elements from the string-array using the adapter.
ArrayAdapter.getItem(position), where position is the index into the array. If you want to get the currently selected item in your Spinner, use Spinner.getSelectedItemPosition() as the parameter to getItem().
This will return a CharSequence because of you your adapter is typed. If you want that values to return as Strings, redefined your adapter as ArrayAdapter<String>
HTH!
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id3) {
final String scale = adapter1.getItem(position);
// scale is gonna be "Centimeters" or "Meters", etc...
if (scale.equals("Centimeters")) {
// do something
} else if (scale.equals("Meters")) {
// do something else
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayAdapter has getItem(int position), which (if you know the position) will get you the String. ArrayAdapter also has getCount(), so you can write a simple for loop to get each element if you don't know its position.
You need to set a OnItemSelectedListener to your spinner. Then in the listener you'll be notified about the selection event. Check the official sample on this: Spinner.

How to get Spinner value?

In Android, I am trying to get the selected Spinner value with a listener.
What is the best way to get the spinner's value?
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
The Spinner should fire an "OnItemSelected" event when something is selected:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Say this is your xml with spinner entries (ie. titles) and values:
<resources>
<string-array name="size_entries">
<item>Small</item>
<item>Medium</item>
<item>Large</item>
</string-array>
<string-array name="size_values">
<item>12</item>
<item>16</item>
<item>20</item>
</string-array>
</resources>
and this is your spinner:
<Spinner
android:id="#+id/size_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/size_entries" />
Then in your code to get the entries:
Spinner spinner = (Spinner) findViewById(R.id.size_spinner);
String size = spinner.getSelectedItem().toString(); // Small, Medium, Large
and to get the values:
int spinner_pos = spinner.getSelectedItemPosition();
String[] size_values = getResources().getStringArray(R.array.size_values);
int size = Integer.valueOf(size_values[spinner_pos]); // 12, 16, 20
Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.
View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();
If you already know the item is a String, I prefer:
String itemText = (String) mySpinner.getSelectedItem();
Calling toString() on an Object that you know is a String seems like a more roundabout path than just casting the Object to String.
add setOnItemSelectedListener to spinner reference and get the data like that`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();

Categories

Resources