I already know how to save edittext contents to sharedpreferences but in spinners and radiogroups I still don't have a clue. Can you please give me snippets of codes how to do it? Thanks
For the data store is is not relevant which UI elements is used to display or modify the value. Here is a description how to store or retrieve various data types: http://developer.android.com/reference/android/content/SharedPreferences.html
So a spinner selection is simply an integer (or string if you like) and the choice for a radio group is simply whatever identifier (as string) you choose to represent that choice.
If the choices come from an array resource you may use the values from the array or the index into the array. Store/retrieve them in/from the shared preferences like you used to store and retrieve the text from the EditText.
This is the way that you can save the selected item of a spinner in sharedPreferences:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object obj = parent.getItemAtPosition(pos);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = prefs.edit();
prefsEditor.putString("object", obj.toString());
prefsEditor.commit();
}
public void onNothingSelected(AdapterView<?> parent) { }
});
Related
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
}
});
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);
Hello I have a profile layout file wherein it saves the data the user inputs. This layout has checkboxes, textviews, and spinners. Then it will be viewed in my userprofile layout file as in textviews. I'm saving them to sharedpreferences. What I'd like to do is retrieve the String value the user selected/saved from spinners, display it in a textview. How can I do this?
I'm wondering how to implement this:
tvbloodtype.setText(prefs.getInt("bloodtype",0));
Any help is truly appreciated. Thanks.
I got error:
ResourcesNotFoundException: String resource ID
After you have your spinner object you can call yourSpinner.OnItemSelectedListener() to get the object that was selected. Then you can save your item in your TextView
yourSpinner.OnItemSelectedListener(new OnItemSelectedListener {
public void onItemSelected(AdapterView <? > parentview, View v, int position, long id) {
curPos = position;
String selected = parentView.getItemAtPosition(position).toString();
tvbloodtype.setText(selected);
}
});
Also reference: How do you get the selected value of a Spinner?
you will need to use String.valueOf() or Integer.toString() for showing Integer in TextView . Example :
tvbloodtype.setText(String.valueOf(prefs.getInt("bloodtype",0)));
OR
tvbloodtype.setText(Integer.toString(prefs.getInt("bloodtype",0)));
write preferences like
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key, value); //key="YOUR_KEY_STRING" //value = your boolean value
editor.apply();
read from preferences
Boolean yourBoolean = prefs.getBoolean("YOUR_KEY_STRING",false); //false = value, if value wasn t set
whenever you are saving your value to sharedPreferences.
SharedPreferences prefs= getSharedPreferences("prf", MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("bloodtype", spinner.getSelectedItem().toString());
edit.commit();
when you are retriving
tvbloodtype.setText(spinner.getString("bloodtype", ""));
I have a spinner like this:
// Spinner 1
final Spinner plan = (Spinner) dialog.findViewById(R.id.spinner1);
strings = getResources().getStringArray(R.array.paymentplan);
sAdapter = new SpinnerAdapter(this,
android.R.layout.simple_spinner_item, strings);
sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
plan.setAdapter(sAdapter);
// plan.setAdapter(spinner1Adapter);
plan.setSelection(prefsDisplay.getInt("spinnerSelection1", 0));
plan.setOnItemSelectedListener(new MyOnItemSelectedListenerPlan());
When user clicks, I want it to save state:
public void onClick(View v) {
Editor editor2 = prefsPlan.edit();
int selectedPosition1 = plan.getSelectedItemPosition();
editor2.putInt("spinnerSelection1", selectedPosition1);
editor2.commit();
}
It saves the position in SharedPref, but the spinner goes back to default. Anyone see something here?
you are storing spinnerSelection
editor1.putInt("spinnerSelection", selectedPosition);
an accessing spinnerSelection1
prefsDisplay.getInt("spinnerSelection1", 0)
make them consistent.
Update
when you are accessing plan.getSelectedItemPosition(). then spinner is visible? I guess NO.
try to put a public variable for selected position. And update selected position in your MyOnItemSelectedListenerPlan. And then store that position in shared preferences. I guess it solve your problem.
to Save:
int selectedPosition = yourSpinner.getSelectedItemPosition()
editor.putInt("spinnerSelection", selectedPosition);
editor.commit();
to Load:
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
if you are array used it should changed like this
String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.commit();
checking array[i] against the value stored in prefs.if you use an
ArrayList instead this part could be done without the loop by calling
ArrayList.indexOf(prefs.getString("spinnerSelection", "");
when you commit show all above array item gone. show no one into
array.
Try below code and first save position of current selected item into one integer variable on onItemSelectedListener() using below code and after that store this variable value into shared preferences.
For Store value into one Variable.
int index;
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
// Here Position is Item Index
index = position;
}
For Store Value into shared preferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt("SelectedIndex", index);
prefsEditor.commit();
And see below link for more information
Android Spinners
Android Shared Preferences
after saving to the preferences, you have to set the selected item to the spinner for further uses
as
int pos = prefsDisplay.getInt("spinnerSelection", "0");
display.setSelection(pos);
but you are using spinnerSelection1. so By default if there is no matching in the preferences. the default value will return. so Here 0 is returned and spinner is set to first position
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.