Getting value from custom SeekBarPreference - android

I found this code on internet and thought I would give it a try. I put it in my preferences and it was exaclt the way I wanted it to be but my only problem is that I cant get the value of SeekBar.
Here is the link to code that I am using in my preference:
http://android.hlidskialf.com/blog/code/android-seekbar-preference
and here is the part of preference xml:
<com.mypack.SeekBarPreference android:key="zoom"
android:title="Zoom"
android:summary=""
android:dialogMessage="Zoom level"
android:defaultValue="50"
android:text=" %"
android:max="100"
/>
can anyone tell me how to get value of seekbar after user has changed it in preferences window?

You could use setOnPreferenceChangeListener():
SeekBarPreference mSeekBarPreference = new SeekBarPreference(this, null);
mSeekBarPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
int value = mSeekBarPreference.getProgress();
// Or you just cast the newValue Object
return true;
}
});

Should be just like any other preference.
implement SharedPreferences.OnSharedPreferenceChangeListener in your activity, then:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( YourActivity.this );
prefs.registerOnSharedPreferenceChangeListener( this );
-
public void onSharedPreferenceChanged( SharedPreferences prefs, String key ) {
mZoomValue = prefs.getInt( "zoom", 50 );
}

Related

How to write a correct if-else statement with sharedPreferences?

I am having a little trouble writing a correct if-else statement for using a checkbox preference to change the background bitmap of my live-wallpaper. Currently I have this method called up:
public void setPreferences(SharedPreferences prefs) {
//Introduce Preference Variables
p = prefs;
//Initialize Preference variables
final boolean mySetting = PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(String.valueOf(R.string.touch), false);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(String.valueOf(mySetting), false);
editor.commit();
//If statement to set preference value
if (prefs.getBoolean(String.valueOf(mySetting), true)) {
GLUtils.texImage2D(GLES10.GL_TEXTURE_2D, 0, nebula, 0);
}else{
GLUtils.texImage2D(GLES10.GL_TEXTURE_2D, 0, stars, 0);
}
}
Where R.string.touch is the key to my checkbox preference in my XML document, like this:
<CheckBoxPreference
android:key="#string/touch"
android:title=""
android:summary=""
android:defaultValue="false"/>
So my question is how could I write a correct if-else statement or even a switch-case statement allowing me to switch the background bitmap? Thank you for any help given.
One issue I see is that String.valueOf(R.string.touch) is going to be giving you an integer as a string rather than the value of the string from your strings.xml.
Here's another way that you could do it:
public void setPreferences() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
final String key = mContext.getString(R.string.touch_setting_key);
final boolean defaultValue = false;
// Read setting's current value.
final boolean currentValue = preferences.getBoolean(key, defaultValue);
// Update setting to true.
preferences.edit()
.putBoolean(key, true)
.apply();
// Use new setting value in an if-statement
final boolean newValue = preferences.getBoolean(key, defaultValue);
if (newValue == true) {
GLUtils.texImage2D(GLES10.GL_TEXTURE_2D, 0, nebula, 0);
} else {
GLUtils.texImage2D(GLES10.GL_TEXTURE_2D, 0, stars, 0);
}
}
Here I'm assuming you're storing your key name in the XML like as follows:
<string translatable="false" name="touch_setting_key">touch_setting_key</string>
As you use the settings in more places, you can store the preferences variable with the class instance as mPreferences and initialize it from onCreate().
You can also store default values in the XML. For a boolean you'd do it like this:
<item name="defaultTouchSetting" format="boolean" type="bool">true</item>
And to read that from code you'd do this:
final boolean defaultValue = mContext.getResources().getBoolean(R.bool.defaultTouchSetting);
Let me know if you're still stuck on anything.
The problem could be in how you are accessing sharedPreferences. In the past, when I have used shared preferences, I used a slightly different aproach: getActivity().getSharedPreferences(). In researching the PreferencManager.getDefault preferences vs Context.getSharedPreferences, I found this post. Android getDefaultSharedPreferences I would try replacing the
PreferenceManager.getDefaultPreferences(mContext);
with
mContext.getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
Where "myAppPrefs" is an arbitrary key.
I hope this helps. Good luck!

onSharedPreferenceChanged without using getDefaultSharedPreferences

I'm using context.getSharedPreference instead of getDefaultSharedPreferences.
Means :
SharedPreferences checkboxSetting = context.getSharedPreferences(
"myPreferenceDB", Context.MODE_PRIVATE);
boolean flag = checkboxSetting.getBoolean("checkboxKey",true);
And preference.xml :
<CheckBoxPreference
android:key="checkBoxPrefff"
android:title="#string/title"
android:defaultValue="true"/>
Application setting has a checkboxpreference that I want to get the value of, checked or not checked.
Will this work?
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equalsIgnoreCase("checkBoxPrefff")) {
sharedPreferences.getBoolean(key,true);
}
}
Does sharedPreferences use default database ( ..._preference.xml ) or my defined database ( "myPreferenceDB" )?
Does key is "checkboxKey" or is null?
Because when I want to get value like
SharedPreferences temp = context.getSharedPreferences(
"myPreferenceDB", Context.MODE_PRIVATE);
boolean flag = temp.getBoolean("checkboxKey",true);
it's wrong and gets back defValue (true) . But when use like
SharedPreferences temp = PreferenceManager.getDefaultSharedPreferences(context);
boolean flag = temp.getBoolean("checkboxKey",true);
it works.
Once again I would like to mention sharedPref is not a DB but rather an XML file. I hope you are looking for the following code.
public class SettingsActivity extends PreferenceActivity {
/*
* (non-Javadoc)
*
* #see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName("myPref");
addPreferencesFromResource(R.xml.pref);
}
You can register a SharedPreferenceChangedListener on any shared pref that you are using. It need not be the default shared preference.
getApplicationContext().getSharedPreferences("myPreferenceDB", 0).registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
}
});

Edit EditTextPreference via code

I have in preferences.xml following EditTextPreference:
<EditTextPreference
android:name="#string/pref_test"
android:defaultValue="0.6"
android:inputType="numberDecimal"
android:key="editTestPref"
android:maxLength="5"
android:summary=""
android:title="#string/pref_test" />
In one of my activities I read the value.
But the problem is if the user enters nothing (""), my app crashes. Sure I could do a if statement in the activity to check if its empty string, but I want to do following:
In Preferences.java I get changes of the preferenceEditText. There I want to set a default value if the user enters "":
if (preference.getKey().equals("editTestPref")) {
if(newValue.equals(""))
{
final SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString("editTestPref", "1");
prefsEditor.commit();
summary = "0.6"; // to update the summary of preference
}
else
{
summary= (String) newValue;
}
}
I also tried this code:
SharedPreferences customSharedPreference = getSharedPreferences(
"myCustomSharedPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference
.edit();
editor.putString("editTestPref", "1");
editor.commit();
Both do not work, they do not update the sharedPreference value. It is still "".
Implement SharedPreferences.OnSharedPreferenceChangeListener like so:
public class YourPrefsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
// ... your existing code ...
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set up a listener whenever a key changes
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ("editTestPref".equals(key)) {
String val = sharedPreferences.getString("editTestPref", "");
if (val == null || val.trim().equals("")) {
val = "0.6"; // <-- your default value
sharedPreferences.edit().putString(key, val).commit();
}
}
}
}
The method is called when the user changed the preferences value, and checks if he entered an empty string. If so, the value is replaced by your default value.
You should rather use if(newValue.isEmpty()) instead of checking the characters
i dont see anything wrong in your code but try this if it works..
Replace this
prefsEditor.putString("editTestPref", "1");
with
prefsEditor.putString("editTestPref", String.valueof(1));
Best Luck.

Android: updating displayed preferences from SharedPreferences

I'm writing an android app with a preferencesActivity in which selections made in my instance of preferencesActivity affect the values of other preferences items displayed. While I'm able to change the values of the underlying SharedPreferences items pogrammatically, those changed values aren't reflected in the displayed list items until I exit my preferencesActivity and reload it. Below is a stripped down version of my settings class and xml file which illustrate the problem. If a user sets Guitar as the value for the preference with the key instrumentList, I'd like the preference with key tuningChoice to revert to Standard.
//necessary import declarations go here
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
Log.d("onSharedPreferencesChanged", "sharedPreferences changed. key: " + key);
Editor preferencesMod = sharedPreferences.edit();
String instrumentChoice = sharedPreferences.getString("instrumentList", "Guitar");
if(key.equals("instrumentList")) {
Log.d("Settings", "key is instrumentList. chooseTuning before if: " + sharedPreferences.getString("chooseTuning", "no luck"));
if(instrumentChoice.equals("Guitar")) {
preferencesMod.putString("chooseTuning", "Standard");
preferencesMod.commit();
Log.d("Settings", "chooseTuning after if: " + sharedPreferences.getString("chooseTuning", "ciao"));
}
}
}
}
xml file preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings">
<ListPreference android:title="Choose an Instrument" android:key="instrumentList" android:entryValues="#array/instruments" android:entries="#array/instruments"/>
<ListPreference android:title="Choose Tuning" android:key="chooseTuning" android:entryValues="#array/tuningChoices" android:entries="#array/tuningChoices" android:persistent="true"/>
</PreferenceScreen>
I can call addPreferencesFromResource again in my onSharedPreferenceChanged method and that loads a duplicate of all the preferences items, displayed below the old items, with the correct values. If I could figure out some way to cancel out the initial addPreferencesFromResource called during onCreate, I guess I would be set.
Any help would be appreciated, Thanks
I do something along these lines...hopefully it helps:
ListPreference list = (ListPreference) getPreferenceManager().findPreference("myList");
list.setValue(sharedPrefs.getString("myList", "default"));
list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
sharedPrefs.put("myList", newValue.toString());
return true;
}
});
You need to prevent addPReferencesFromResource from running twice? Is this loading your default values? If so, add an additional SharedPreference called DEFAULTS_LOADED and read its value in on create like: (WARNING PSUEDO CODE):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean loadDefaults = app_preferences.getBoolean(DEFAULTS_LOADED, true);
if(loadDefaults)
{
addPreferencesFromResource(R.xml.preferences);
Editor editor = app_preferences.edit();
editor.putBoolean(DEFAULTS_LOADED, true);
editor.commit();
}
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
This will prevent you defaults from being written to the shared preferences every time your activity starts. I assume this is at least a portion of your issue.
If anyone comes to this problem, this is the solution:
ListView list = preferenceActivity.getListView();
list.performItemClick(list, 1, list.getItemIdAtPosition(1));
Maybe I am too late for answering this. But, I hope this might help beginner like me.
PackageInfo packageInfo = null;
try {
packageInfo = preference.getContext().getPackageManager().getPackageInfo(preference.getContext().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
preference.setSummary(packageInfo.versionName);

OnPreferenceChangeListener for every setting

I know that I can do something like this:
Preference pref = findPreference(getString(R.string.pref_vibrate_on_key));
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
LogUtil.d("Working!");
return true;
}
});
But I would like to add a Listener to every preference.
I tried doing:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
LogUtil.d("working!");
}
});
but it doesn't work.
Is this possible? If so, what am I doing wrong?
Assuming you want the same listener called each time, this might be a simpler solution:
Preference.OnPreferenceChangeListener changeListener = new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Code goes here
return true;
}
};
EditTextPreference pref = (EditTextPreference)findPreference(getString(R.string.pref1));
pref1.setOnPreferenceChangeListener(changeListener);
EditTextPreference pref2 = (EditTextPreference)findPreference(getString(R.string.pref2));
pref2.setOnPreferenceChangeListener(changeListener);
I think that onSharedPrefererenceChanged is fired upon saving the preference (when you click BACK or HOME in PreferenceActivity). I think that the easiest way is to create single class implementing OnPreferenceChangeListener and switch through Preference.getKey(); and set it as OnPreferenceChangeListener for each Preference.

Categories

Resources