How to Get Selected Text and Value Android ListPreference - android

The XML file of my ListPreference
<ListPreference android:key="lpBirim" android:title="Birim"
android:summary="" android:defaultValue="0" android:persistent="false"/>
How to get the selected text and the selected value?

in your PreferenceActivity do something like:
ListPreference listPreference = (ListPreference) findPreference("lpBirim");
CharSequence currText = listPreference.getEntry();
String currValue = listPreference.getValue();

You can use this snippet to get the value:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.getString("lpBirim","-1")
Have look on the tutorial

Here is an example:
#Override
public boolean onPreferenceChange(Preference preference, Object value)
{
String textValue = value.toString();
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(textValue);
CharSequence[] entries = listPreference.getEntries();
if(index >= 0)
Toast.makeText(preference.getContext(), entries[index], Toast.LENGTH_LONG);
return true;
}
index contains the index of the clicked item
textValue is the Selected Value
entries[index] is the Selected Text

SharedPreferences Preference = PreferenceManager.getDefaultSharedPreferences(this);
Preference.getString("your list preference key","-1")

You can use findPreference() to get a ListPreference that has all methods you need. To have it working you need to use or extend PreferenceFragment first.

Related

How to retrieve spinner value from sharedpreferences? ANDROID

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", ""));

save value of spinner selected item

How can I save the current selected spinner value, such that when I reopen the application the saved value is automatically selected by default?
Please Write below code on onItemSelectedListener() of spinner and store selected value into shared preferences.
String mSpnValue=mSpinner1.getSelectedItem().toString();
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Value", mSpnValue);
Use below code for set item as selected in spinner.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String myString = myPrefs.getString("Value","nothing"); // the value you want the
ArrayAdapter<String> myAdap = (ArrayAdapter<String>) mSpinner1.getAdapter();
int spinnerPosition = myAdap.getPosition(myString);
// set the default according to value
mSpinner1.setSelection(spinnerPosition);
You can save spinner position in preferences and when entering back use spinner.setSelection(position_from_preferences);
You can use several methods
For example you can use a DataBase and save on it.
Other methods, and the best IMO, is used SharedPreferences
http://developer.android.com/intl/es/reference/android/content/SharedPreferences.html
http://developer.android.com/intl/es/reference/android/app/backup/SharedPreferencesBackupHelper.html
For set value one another way:---
for(int i=0;i<adapter.getCount();i++){
if(adapter.getItem(i).equals(your save preference value){
spinner_timer.setSelection(i);
}
}
you can also refer to the spinner value by position. that way you need only to deal with ints straight-fowardly:
SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("VALUE", spinner.getSelectedItemPosition());
editor.commit();
and to load:
spinner.setSelection(settings.getInt("VALUE", 0));

Save and Retrieve Selected Spinner Position

How would you save and retrieve a spinners selection, so when you come back the same item on the spinner is selected? Maybe with shared preferences?
to Save data on the sharedPreferences( put this code on the onItemSelected() method and save the selected value's position of your spinner) :
int userChoice = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner",usersChoice);
prefEditor.commit();
To get data from sharedPreferences :
SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",-1);
if(spinnerValue != -1) {
// set the selected value of the spinner
spinner.setSelection(spinnerValue);
}
refer this : set selection in spinner
and this : get the position of the selected item in a spinner
See Also :
Android Tutorial : Using SharedPreferences
Android Tutorial : Switch Between Activities and Pass Data Between Them

ANDROID Preference Activity not setting default value

I have a preference activity and have noticed that a list preference does not set default values when changed.
The Preference has these basic dynamics
If Checkbox = unticked --> list preference entry values = x
if Checkbox = ticked --> list preference entry values = z
When the app first runs default value is set but when I tick the checkbox no values apply after that.
CODE:
public class QuickPrefsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
View title =(View)getWindow().findViewById(android.R.id.title);
FrameLayout titlebar=(FrameLayout)title.getParent();
TextView txt = (TextView)titlebar.getChildAt(0);
txt.setGravity(Gravity.CENTER);
CheckBoxPreference chckbox = (CheckBoxPreference)
findPreference("french");
if (chckbox.isChecked()) {
ListPreference newsPref = (ListPreference)
findPreference("news_feed");
newsPref.setEntryValues(getResources().
getStringArray(R.array.newsfeedfr));
newsPref.setDefaultValue(1);
} else {
ListPreference news2Pref = (ListPreference)
findPreference("news_feed");
news2Pref.setEntryValues(getResources().
getStringArray(R.array.newsfeed));
news2Pref.setDefaultValue(1);
}
}
}
you need to add onPreferenceChangeListener like below...
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("french");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("true") {
// add your code here if checkbox is checked.
}
else {
// add your code here if checkbox is not checked.
}
return true;
}
});
Method setDefaultValue() takes an Object as argument, rather than index in values array. So, you should rewrite your code something like this:
String[] values = getResources().getStringArray(R.array.newsfeed)
news2Pref.setEntryValues(values);
news2Pref.setDefaultValue(values[0]);
Moreover, you should probably set entry titles too:
news2Pref.setEntries(your_titles_array_here);

Spinner value into a ListPreference

I'm trying to save a Spinner value into a ListPreference. I can't get it to work. I've tried to get this working for a long time now. Does anyone have a solution or can anyone point me in the right direction.
So this is what I have:
SharedPreferences preferences;
private static final String KEY_WEIGHT_PREFERENCE = "weightunit";
...
preferences = PreferenceManager.getDefaultSharedPreferences(this);
...
This is the main part, both the Spinner and the ListPreference grab the same data from an array xml.
SharedPreferences.Editor edit = preferences.edit();
Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
int selectedPosition = weight.getSelectedItemPosition();
edit.putInt(KEY_WEIGHT_PREFERENCE, selectedPosition);
edit.commit();
Thanks!
What isn't working?
There's a sample app called Spinner that contains a sample Spinner. It saves the state of the Spinner to saved preferences in onPause(), and restores it in onResume().
I found the answer, the SpinnerValue needs to be saved as a string in order to get recognized by the ListPreference.
Here's my final code:
private void updatePreferenceWeightValue() {
SharedPreferences.Editor edit = preferences.edit();
Spinner weight = (Spinner) findViewById(R.id.weightUnitSpinner);
int selectedPosition = weight.getSelectedItemPosition();
String weightValue = "";
weightValue = Integer.toString(selectedPosition);
edit.putString(KEY_WEIGHT_PREFERENCE, weightValue);
edit.commit();
}

Categories

Resources