Persisting spinner selected value - android

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.

Related

The right way to save spinner to sharepreferences

I have a spinner that have 3 values populated from array-list.
I want to save the spinner selected value to shared preferences so it can be loaded back again when the use comes back to the app. What is the correct way to do this (to avoid future problems)
1- Save position of the selection
2- Save the text of the selection
3- Get the position/text of the selection, get the corresponding enum, and save the enum name.
I am leaning towards the 3rd option incase the positions/texts changed in later updates but I am wondering what is the correct way of doing such task
Thank you
Save position (1 variant) and text (2 variant) are bad practice. Because text for your spinner items may will change in the future and their position can be changed.
I think, that you need to create enum or #TypeDef element and save it to sharedPreferences. #TypeDef is more performance but enum is more functionality (if you use Kotlin you can use sealed classes). For this solution just write mapper that can map enum to spinner item.
If you use enum, the best way is to save it name ENUM.name().
Read carefully and understand. Get the post and use at your own understanding.
Declare your spinner and sharedPreferences
public Spinner crimeType;
SharedPreferences sharedPreferencesFirstTime;
//////
sharedPreferencesFirstTime = getPreferences
(Context.MODE_PRIVATE);
String firstTime = getResources().getString(R.string.saved_first_time);
firstTimekey = sharedPreferencesFirstTime.getString
(getString(R.string.saved_first_time),
firstTime);
crimeType = v.findViewById(R.id.crimeType);
Initializing a String Array
String[] plants = new String[]{
"Antisocial behaviour",
"Arson",
"Burglary"
};
Initializing an ArrayAdapter
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(
getActivity(), android.R.layout.simple_spinner_item, plants
);
Sets the layout resource to create the drop down views.
/*
Parameters : resource
the layout resource defining the drop down views
*/
spinnerArrayAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
Sets the Adapter used to provide the data which backs this
/*
setAdapter(SpinnerAdapter adapter)
Sets the Adapter used to provide the data which backs this Spinner.
*/
crimeType.setAdapter(spinnerArrayAdapter);
crimeType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get the text content
crime_string= parent.getItemAtPosition(position).toString();
//Get Position of the crime
selectionPosition=
parent.getItemAtPosition(position);
SharedPreferences.Editor editor = sharedPref.edit();
String key2 = crime_string;
editor.putString(getString(R.string.saved_login_key), key2);
editor.apply();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Another interface callback
}
});

How to save state of spinner using Java Android

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.

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...

Display default value when I nothing selected from spinner array android

I make a spinner put the value in spinner using array,now even I was not select any value from spinner it automatically takes first value from spinner array, I want to set default value when nothing is selected form spinner array by user,means I get default value which I set ,when I was not selected any value, is this possible, and what is the use of onNothingSelected(AdapterView ....below code should run when user select manually any value from spinner but it run always and get first value which is in array,so please tell how to get default value when I nothing selected from spinner, can I use on nothing selected method..?
ArrayAdapter<String> CurrencyAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, Currency);
currency.setAdapter(CurrencyAdapter);
currency.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
Better set first value of array,the value what you want to set as default. And then you can check whether that value is selected or something else to figure out,is spinner selected or not??
A related question I asked a couple of days ago could help you here, have a look at How to use Android Spinner like a drop-down list and see some of the answers which I found helpful.
And no, onNothingSelected() does not do what you're after... you want to have a look at the methods setSelection() and setSelectionInt() in the question I referred to.

How do I set spinner value to string

I have a spinner set up like this:
ArrayAdapter<String> states = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.stateabbrev));
states.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
state.setAdapter(states);
As you can see, the source is an array.xml file.
I want to know how to populate it if I know the array value. For instance, I am retrieving information from my database and the user is from "KY" so I have a string "KY" and I want the spinner selection to be on "KY"
at first we should get position of "KY"
int position = states.getPosition("KY");
after that, select in spinner with position
state.setSelection(position);

Categories

Resources