I am trying to save the state of a spinner select. So if I select a choice in the spinner and move into a different activity, then coming back to the activity with the spinner that choice should still be selected. I found some tutorials but the ones of I have tried are deprecated.
Here's my spinner:
//language selection list
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.language_list, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// storing string resources into Array
lang_list = getResources().getStringArray(R.array.language_list);
Toast.makeText(getBaseContext(), "You have selected : " + lang_list[index],
Toast.LENGTH_SHORT).show();
choice = spinner.getSelectedItem().toString();
final ImageView country_flag = (ImageView)findViewById(R.id.country);
String s=((TextView)arg1).getText().toString();
if(s.equals("English"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.eng_spinner));
if(s.equals("German"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.german_spinner));
if(s.equals("French"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.french_spinner));
if(s.equals("Spanish"))
country_flag.setImageDrawable(getResources().getDrawable(R.drawable.spanish_spinner));
}
Save the current spinner's state on onSaveInstanceState() by putting the date, time, etc. into the bundle with a key by getting the index of the spinner's current selected position. Afterwards, on your onCreate(), check if bundle == null, and if it is not null (which it shouldn't be if your activity was recreated due to resume), you retrieve the values you stored in it with the keys. Finally, manually set the values to your spinner using Spinner.setPosition() inside the onCreate().
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
This should be a good read.
Related
What I have is a Settings activity on which I choose the language via spinner. When I change it to Russian for example the language changes, but when I open the Settings menu again the selected item on the spinner is the first item (English) and not the current one (Russian).
This is my spinner
Resources res = getResources();
language = res.getStringArray(R.array.languages_arrays);
Spinner spinner = (Spinner) findViewById(R.id.toolbar_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, R.layout.spinner_item_dropdown,
language);
spinner.setAdapter(adapter);
What do I need to change in the spinner in order to show the selected language?
If you want to set the previous selected item of a spinner you have to store the selected item and then set your selection :
here's an example wish i'am getting my previous selected item then fetching the item's position from he's array adapter
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String language = preferences.getString("language", "");
if(!language.equalsIgnoreCase(""))
{
int spinnerPosition = arrayAdapter.getPosition(language);
spinner.setSelection(spinnerPosition);
}
You can store your data as below :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putString("language",spinner.getSelectedItem().toString(););
editor.apply();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
For that u need to set spinner value programatically
for (int i=0 ;i<languages.length;i++)
{
if(languages[i] = "RUSSIAN")//change it according to ur prrefence
spinner.setSelection(i);
}
You have to save previous selected value somewhere in your app. When you open setting again check for that value and find position of it in array. Once you find location of it set Spinner selection to that position like below:
spinner.setSelection(position_of_selected_item);
I have a spinner and I want to get the last selected value of it when I click on the spinner (basically just before the items in the list are being shown).
How can I achieve this?
Update:
Example: There are a dynamic amount of spinners. User clicks in spinner 1 and selects a value, let's say "house". Then clicks somewhere else. Then clicks in spinner 1 again. What I now need is to return the value "house" that was previously was selected before the user selects a different value i.e. "car" in that spinner. I can not use the local storage to save that value beforehand because it's going to be a dynamic amount of spinners to be added.
And yes, I did in fact read the documentation at http://developer.android.com/guide/topics/ui/controls/spinner.html already but what I need isn't explained there.
Maybe you can declare a String array and then use it to storage the items values. Showing this in a TextView is a way to see if it works.
Something like this:
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
selection.setText(items[arg2]);
}
I already have faced a similar situation, but I don't remember exactly how I solved it. Tell me if it gives a better idea to you, I'm new participating here.
Spinner mySpinner=(Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
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);
IN YOUR CASE:
TO se if the user clicked on the spinner, do this:
if (spin.getSelectedItemPosition() < 0) {
Spinner mySpinner=(Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
}
This means user clicked the spinner, but not any items of it.
EDIT AGAIN
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
> ...
>
> public void onItemSelected(AdapterView<?> parent, View view,
> int pos, long id) {
> parent.getItemAtPosition(pos) //THIS GETS YOU THAT VALUE THAT THE USER CLICKED ON DYNAMICALLY
> }
>
> public void onNothingSelected(AdapterView<?> parent) {
> // Another interface callback
> }
> }
http://developer.android.com/guide/topics/ui/controls/spinner.html
Solution is to add a TextView widget with each added Spinner. Set the TextView to "gone" (not visible). When the spinner changes set the value to that TextView. This way you can store the last selected spinner value in the TextView. When the user clicks on the spinner and changes the value you can still access the previously selected/unselected value from the spinner through the TextView widget.
// Use this TextView to temporarily store the spinner value
final TextView hiddenTextView = new TextView(getContext());
hiddenTextView.setVisibility(View.GONE);
final Spinner spinner = new Spinner(getContext());
spinner.setPrompt(getString(R.string.email_other));
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.email_types, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.d(TAG, "TextView Value before spinner change: " + hiddenTextView.getText());
String spinnerValue = String.valueOf(spinner.getSelectedItem());
hiddenTextView.setText(spinnerValue);
Log.d(TAG, "TextView Value after spinner change: " + hiddenTextView.getText());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
return;
}
});
In my application I have 1 spinner option. In that I am displaying 6 values (which is array from values file). Now in that when I click its 5 items of the spinner value the selected item will show in the spinner in the activity screen.
When I select 6th item in spinner I have to start a new activity. Is it possible? Do I have to do this by position value?
Also in the new activity (after selecting 6th item) I have 5 edittext values in which user can enter a string which should replace the old value in the spinner. Is it possible to dynamically update the spinner?
My spinner code:
Spinner s2=(Spinner)findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.group_array, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter1);
It's possible
Codings:
ArrayAdapter yearadp = new ArrayAdapter(this,android.R.layout.simple_spinner_item, yearlist);
yearadp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
year_spinner.setAdapter(yearadp);
index=0;
year_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
spintext=parent.getItemAtPosition(pos).toString();
if(spintext=="6")
{
intent = new Intent(ListMonthActivity.this,NewChart.class);
startActivity(intent);
}
}
}
Ya we can do with setting with
mon_spinner.setSelection(iSelectedMonth);
intent = new Intent(ListMonthActivity.this,NewChart.class);
You may or not mention while the action are certain action finished, and you can passed into another activity .
I'm trying to use the spinner object in my app, but I'm having trouble, in fact, it is activated at the start of my activity. While I wish it was enabled when was clicked and selected the desired item.
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.ElementaryOperations, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
index1 = s1.getSelectedItemPosition()+1;
if (index1 == 3){
finish();
startActivity(prod);//
}
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
spinner listener OnItemSelectedListener is called when you start activity due to get default value.i mean first element and zeroth index. so you can check if position is zero then dont anything.but mind that you cant achieve default selected value.if you put condition for zero.
if cant work proper than see this question
In the following code I am setting up a spinner, listening and detecting selections from the spinner.
The problem is I am trying to save the previously selected value so it is persistent between activity reloads, but when I reload the activity, the previously selected value is not set as the spinner value. The code is as follows :
final Spinner spinner = (Spinner)findViewById(R.id.Spinner_gender);
ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this, spinnerID, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View itemSelected, int selectedItemPosition, long selected){
Editor editor = mGameSettings.edit();
editor.putLong(GAME_PREFERENCES_GENDER, selectedItemPosition);
editor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
//if( mGameSettings.contains(GAME_PREFERENCES_GENDER) ){
Toast.makeText(QuizSettingsActivity.this, "Detected(again): " + spinner.getSelectedItemPosition(), Toast.LENGTH_SHORT).show();
spinner.setSelection( spinner.getSelectedItemPosition() );
//}
I am using spinner.getSelectedItemPosition() to get the spinner selected index. Can anyone please tell me what I am doing wrong?
You are never reading from your SharedPreferences. You are writing to them (at least, I assume that is what mGameSettings is), but not reading from them.
spinner.setSelection( spinner.getSelectedItemPosition() );
This is a nonsense statement. You are setting the spinner's selection to its current selection. If you want to set the spinner's selection to the value from your SharedPreferences, you need to read the value from the SharedPreferences.
I found a solution to persisting the state of spinners in Android apps in simple situations.
In my app my spinner had three values (Normal, Important, and Urgent). Initially, these values were stored in a SQLite database as strings.
My solution involved storing the spinner values instead as integers in the SQLite database and then using the following code to set the spinner value when the activity was reloaded:
int temp = (int) memo.getInt(memo.getColumnIndexOrThrow(MemoDbAdapter.KEY_MODE));
mModeText.setSelection(temp);
This allowed me pass the data from the SQLite database directly without having to work out the position of desired selection from strings stored in the database. This worked for my simple Memo application but obviously won't work if you need to store the spinner output as strings in your database.