New to Android, I have some code when the user changes a preference I update the Summary field in the UI preference to be the value they entered. However, when the preference activity is created I'd like to set the Summary fields to be the values in the corresponding preferences.
Please advise. Thanks.
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
sp.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Preference pref = findPreference(key);
if (pref instanceof EditTextPreference) {
EditTextPreference etp = (EditTextPreference) pref;
pref.setSummary(etp.getText());
}
}
}
I am new too so may not be the best code but this is similar to what I am doing. You probably want to register you listener onResume and unregister it onPause though rather than onCreate. I hope this helps.
Mainly you just need to grab the pref, the pref value and set the summary.
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
EditTextPreference editTextPref = (EditTextPreference) findPreference("thePrefKey");
editTextPref
.setSummary(sp.getString("thePrefKey", "Some Default Text"));
}
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Preference pref = findPreference(key);
if (pref instanceof EditTextPreference) {
EditTextPreference etp = (EditTextPreference) pref;
pref.setSummary(etp.getText());
}
}
}
This worked for me.
public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
private Preference pref;
private String summaryStr;
String prefixStr;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
SharedPreferences sharedPref = getPreferenceScreen().getSharedPreferences();
sharedPref.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
//Get the current summary
pref = findPreference(key);
summaryStr = (String)pref.getSummary();
//Get the user input data
prefixStr = sharedPreferences.getString(key, "");
//Update the summary with user input data
pref.setSummary(summaryStr.concat(": [").concat(prefixStr).concat("]"));
}
}
What I usually do is:
1 - Make a new class which extends the kind of preference I need to show (1 per preference type)
2 - Inside its code, do the appropriate actiob to show the updated summary
3 - Refer this class in the res/xml/preferences.xml file
Let me swo a small example, good for an EditTextPreference:
CLS_Prefs_Edit.java
/**
* CLS_Prefs_Edit class
*
* This is the class that allows for a custom EditTextPrefence
* (auto refresh summary).
*
* #category Custom Preference
* #author Luca Crisi (luca.crisi.lc#gmail.com)
* #copyright Luca Crisi
* #version 1.0
*/
package com.your_name.your_app;
/* -------------------------------- Imports --------------------------------- */
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
public final class CLS_Prefs_Edit
extends EditTextPreference
{
/* ---------------------------- Constructors ---------------------------- */
public CLS_Prefs_Edit(final Context ctx, final AttributeSet attrs)
{
super(ctx, attrs);
}
public CLS_Prefs_Edit(final Context ctx)
{
super(ctx);
}
/* ----------------------------- Overrides ------------------------------ */
#Override
public void setText(final String value)
{
super.setText(value);
setSummary(getText());
}
}
res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
>
<PreferenceCategory android:title="#string/pref_phone_cat">
<!-- NORMAL EditTextPreference, NO summary update -->
<!-- <EditTextPreference -->
<!-- android:widgetLayout="#layout/arr_dn" -->
<!-- android:key="phone" -->
<!-- android:title="#string/pref_phone_title" -->
<!-- android:summary="#string/pref_phone_summ" -->
<!-- android:defaultValue="" -->
<!-- android:inputType="phone" -->
<!-- android:digits="+1234567890" -->
<!-- /> -->
<!-- MY EditTextPreference, WITH summary update -->
<com.your_name.your_app.CLS_Prefs_Edit
android:widgetLayout="#layout/arr_dn"
android:key="phone"
android:title="#string/pref_phone_title"
android:summary="#string/pref_phone_summ"
android:defaultValue=""
android:inputType="phone"
android:digits="+1234567890"
/>
</PreferenceCategory>
</PreferenceScreen>
Of course, set your strings in /res/values/strings, and you're done.
Note that this solution works for both PreferenceFragments and PreferenceActivities.
I'm using it for an app tha runs on 2.2 Froyo (showing a PreferenceActivity) as well as on 4.4 KitKat (showing a PreferenceFragment)
I hope it helps.
First, for your class:
class SettingsFragment : SettingsBaseFragment(),
// Make sure you implement the OnSharedPreferenceChangeListener
SharedPreferences.OnSharedPreferenceChangeListener,
Preference.OnPreferenceClickListener {}
Next, in the onSharedPreferenceChanged, you have a reference to the sharedPreference, which you can use to get the preference result. Then you can use the latest result you get to alter the summary:
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
when (key) {
SETTINGS_AUTO_SETTLEMENT -> refreshSummaryForAutoSettlement(sharedPreferences?.getBoolean(SETTINGS_AUTO_SETTLEMENT, false))
}
}
// helper function for altering the summary for the preference
private fun refreshSummaryForAutoSettlement(isAutoSettlementEnabled: Boolean?) {
when (isAutoSettlementEnabled != null && isAutoSettlementEnabled) {
true -> findPreference(SETTINGS_AUTO_SETTLEMENT).summary = getString(R.string.auto_settlement_enabled_summary)
false -> findPreference(SETTINGS_AUTO_SETTLEMENT).summary = getString(R.string.auto_settlement_disabled_summary)
}
}
Related
Because I want an AppCompat Action Bar on all of my settings submenus, I had to implement a workaround and my Settings Activity extends AppCompatActivity, not PreferenceActivity. I'm using a PreferenceFragment in the activity to handle the preferences, and each PreferenceScreen has its own xml file, which the PreferenceFragment switches out for each submenu in the settings. All of this was necessary to get the Action Bar to stay put through all of my submenus.
I'm trying to read a string value from the shared preferences file from within my MainActivity, and I've tried three different methods for getting that information, none of which have worked:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
,
SharedPreferences sharedPref = getSharedPreferences(name, MODE_PRIVATE);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
and
SharedPreferences sharedPref = getPreferences(MODE_PRIVATE);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
Here is the relevant section of my preferences.xml:
<PreferenceCategory
android:title="Bluetooth"
android:key="pref_bt">
<Preference
android:title="Select Bluetooth Device"
android:key="#string/bt_select_key"
android:defaultValue="0">
</Preference>
</PreferenceCategory>
This should fill the btSelectPref string with a "0", but it's always empty when I test it. I have included PreferenceManager.setDefaultValues(this, R.xml.preferences, false); in onCreate in my MainActivity, so the default values should be set.
I'm not sure which of these methods I should be using since I have multiple resource files for my settings, but none of them seem to be working for me. In the case of getSharedPreferences(name, MODE_PRIVATE), I have no idea what the name parameter should be referencing, since I've never named my shared preferences file.
EDIT: It turns out my issue was not related to getting values from the shared preferences file. I just had the wrong xml tag on the preference I was trying to check the value of. I changed it from a generic <Preference> tag to a <ListPreference> and my code started working with PreferenceManager.getDefaultSharedPreferences().
What you want to do and what you are doing differs. If you just want to put default shared preference for a key then consider this example. If your whole activity has just one shared pref file then you need not specify any name. It will automatically get it.
public MainActivity extends AppCompatActivity {
SharedPreferences mPrefs;
int test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
mPrefs = this.getPreferences(Context.MODE_PRIVATE);
test = mPrefs.getInt("pref_bt_select", 0);}
}
For the above example you can define the key and default value in your strings.xml and then you can refer to it while looking for the prefs you want.
Hey I have used AppCompat for my preference screen too.I did this because I wanted to use Vintage Chroma and this was the only way. But I am able to use PreferenceManager.getDefaultSharedPreference() without any errors.
Also if you want to use default shared preferences in the Fragment you can use :
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Here is my full code :
public class PreferencesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new PreferencesScreen())
.commit();
ActionBar toolbar = getSupportActionBar();
if (toolbar != null) {
toolbar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public static class PreferencesScreen extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_xml);
}
}
}
Here is my code snippet for MAinActivity
Just the initial part where I set the default text theme.
`public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
AutoCompleteTextView mytextview;
public static String[] list;
ArrayList<String> recent = new ArrayList<String>();
public int recent_index = 0;
Menu mMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
/*Setting default theme.*/
SharedPreferences Sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int firstRun=Sp.getInt("firstRun",0);
if(firstRun==0)
{
SharedPreferences.Editor editor=Sp.edit();
editor.putInt("paragraphFontColor", Color.parseColor("#ffffff"));
editor.putInt("headingFontColor",Color.parseColor("#DE5246"));
editor.putInt("subheadingFontColor",Color.parseColor("#597d5e"));
editor.putInt("hyperlinksFontColor",Color.parseColor("#A5D8F5"));
editor.putInt("bodyColor",Color.parseColor("#2b2b2b"));
editor.putString("paragraphFont","PrintClearly.otf");
editor.putString("headingFont","PrintBold.otf");
editor.putString("subheadingFont","PrintBold.otf");
editor.putString("hyperlinkFont","PrintBold.otf");
editor.putString("paragraphFontStyle","normal");
editor.putString("headingFontStyle","normal");
editor.putString("subheadingFontStyle","normal");
editor.putString("hyperlinkFontStyle","normal");
editor.putString("actionBarColor","#597d5e");
editor.putString("paragraphFontSize","20px");
editor.putString("headingFontSize","30px");
editor.putString("subheadingFontSize","20px");
editor.putString("hyperlinkFontSize","20px");
editor.putString("firstRun",0);
editor.commit();
}
`
I am implementing the Settings for my android app through the PreferenceFragment.
My android:summary for the different Preferences should display the current value at all times therefore I have read through severals posts and the official documentation.
Although I got it working technically my solution seems kind of hacky and I am now searching for best practice since I found no good source on how it is meant to be properly implemented.
For example I implemented onSharedPreferenceChanged to listen for changes and to update the UI, but after every restart of the PreferenceFragment, the initial android:summary is shown again. To solve this I added this to the onCreate
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
Is this is how it is supposed to be done or am I misunderstanding something ?
Full Code:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SERVER_ADDRESS = "serverAddress";
public static final String KEY_PREF_GENDER = "gender";
public SettingsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
//Load the preferences from the XML file
addPreferencesFromResource(R.xml.preferences);
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
}
// Listen for settings changes and update the UI
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PREF_SERVER_ADDRESS)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
if (key.equals(KEY_PREF_GENDER)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
I have a ListPreference containing colors. Only when I restart the application that the colors are being changed, not directly. How do I make it change directly when I click ?
public class Preferences extends PreferenceActivity {
SharedPreferences sharedpreferences;
SharedPreferences sharedpreferences2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
sharedpreferences2 = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
ListPreference listPreference = (ListPreference) findPreference("Color");
CharSequence entry = listPreference.getEntry();
final String value = listPreference.getValue();
final ListView rel = this.getListView();
if (sharedpreferences2.contains("Color")) {
if (value.toString().equals("Red")) {
rel.setBackgroundColor(Color.RED);
}
if (value.toString().equals("Blue")) {
rel.setBackgroundColor(Color.BLUE);
}
if (value.toString().equalsIgnoreCase("Green")) {
rel.setBackgroundColor(Color.GREEN);
}
}
}
you will need the OnSharedPreferenceChangeListener. Use registerOnSharedPreferenceChangeListener() in your onResume() and override the onSharedPreferenceChanged() method to perform actions on preference change.
Unregister the listener in your onPause() method.
P.S. PreferenceActivity is deprecated, consider using PreferenceFragment instead.
I am new to creating PreferenceActivity. My question is how to enable and disable option in preference screen by changing other preference?
My prefs.xml:
<ListPreference
android:entries="#array/units"
android:entryValues="#array/lunits"
android:key="listUnits"
android:summary="Units schosssing"
android:title="Units" android:defaultValue="C"/>
<ListPreference
android:entries="#array/palette"
android:entryValues="#array/lpalette"
android:key="listpalette"
android:summary="Palette schosssing"
android:title="Palette"
android:defaultValue="1"/>
In the listUnits there are 2 options, Celsius and Fahrenheit, so if user selects Celsius the listpalette should get enabled, and if user selects Fahrenheit becomes disabled, how can I do this?
My settings activity:
public class SettingsActivity extends PreferenceActivity
{
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
}
This code may be useful to you. Can take as reference.
First take instance of both of the ListPreference and apply this method.
ListPreference mlistUnits, mlistPalette;
mlistUnits= (ListPreference)findPreference("listUnits");
mlistPalette= (ListPreference)findPreference("listpalette");
mlistUnits.setEnable(false);
mlistPalette.setEnabled(true);
and use below listner
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// newValue is the value you choose
return false;
}
};
apply listener to ListPreference
mlistPalette.setOnPreferenceChangeListener(listener);
Firstly you can set default value for your listUnits listpreference to celcius or Fahrenheit ,according this you can make enable-disable your second listpreference.
Now when changing your Preference by selecting anyone of them you can follow below procedure.
1) implement OnSharedPreferenceChangeListener in your MyPreferenceFragment class and override the method onSharedPreferenceChanged
2) Code like below in your method
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if (key.equals("listUnits")) {
final String value = sharedPreferences.getString(key, "");
Preference Pref_cec=findPreference("listpalette");
if (value.equals("celcius")) {
wallpaperPref_admin.setEnabled(true);
}else{
wallpaperPref_admin.setEnabled(false);
}
}
}
Hope it will Help. Let me know if anything missing in my post.
As your second list is evaluated on basic of first list, what you may do
Look for preference click on the First list, get the value of preference clicked.
Using this value simply enable/disable your second list.
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
}
});