Run Method when Preference is Updated - android

How would I add a listener so that when a preference is changed (i.e. CheckBoxPreference) some
method is executed (i.e. Toast)
Preferences.java
public class Preferences extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Main.java
[...]
SharedPreferences preferences;
preferences = PreferenceManager.getDefaultSharedPreferences(this);
[...]

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/AdvancedPreferences.html

Related

show sharedpreference on preference activity

I'm struggling to figure out how to show the preference in the preference activity. I'm simply trying to show the high score and i keep getting the same 345 value show up. I have confirmed in debugging that the new high score is saved . Here is all my code.
preferences.xml
<Preference
android:title="High Score"
android:selectable="false"
android:defaultValue="0"
android:key="#string/pref_highest_score"/>
HighScoreActivity.java
public class HighScoreActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new HighScoreFragment()).commit();
}
public static class HighScoreFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onResume(){
super.onResume();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
}
strings.xml
<!-- High Score settings -->
<string name="pref_highest_score">345</string>
<string name="title_activity_high_score">High Score</string>
MainActivity.java
preferences = PreferenceManager.getDefaultSharedPreferences(context);
Assets.highScore = preferences.getInt(context.getString(R.string.pref_highest_score), 1);
editor = preferences.edit();
editor.putInt(context.getString(R.string.pref_highest_score), currentPoints );
editor.apply();
It's because your preference screen does not actually gets the value of pref_highest_score. You should find the preference and call Preference.setSummary(). Like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Gets the preference defined in XML
Preference p = findPreference("#string/pref_highest_score");
// Sets the summary of the preference to the high score
p.setSummary(
String.valueOf(preferences.getInt(context.getString(R.string.pref_highest_score), 1))
);
}
where preferences is PreferenceManager.getDefaultSharedPreferences(context).
And in your XML, specify an id of the preference:
<Preference
android:key="#string/pref_highest_score"
android:title="High Score"
android:selectable="false"
android:defaultValue="0"/>

Android SharedPreferences confusion

I am a beginner in android and I have a confusion regarding Shared Preferences implementation. My goal is to use a string where a user defines some text which will be used in MainFragment. Given the fact that user may change that string when application is running I need a listener as well. So according to one book so far I have a SettingsActivity and a SettingsFragment.
SettingsActivity so far:
public class SettingsActivity extends AppCompatActivity {
private SharedPreferences prefs;
private String stringIWantToSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getFragmentManager().beginTransaction().
replace(android.R.id.content, new SettingsFragment(), "settings_fragment").commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
protected void onResume() {
super.onResume();
stringIWantToSave = prefs.getString("stringIWantToSave", "myString");
}
}
SettingsFragment so far:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences sharedPreferences;
private String stringIWantToSave;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
#Override
public void onPause() {
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onResume() {
super.onResume();
sharedPreferences.getString("stringIWantToSave", "myString");
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
My questions are:
• In which method and how should I save the changed value from the user?
• How can I implement the listener so that it will inform the MainFragment that the string has changed?
1. To achieve the SettingsActivity with EditTextPreference, first you have to create a PreferenceScreen that contains EditTextPreference.
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="pref_key_name"
android:title="Name"
android:summary="Enter your name here!"
android:dialogTitle="Enter name:">
</EditTextPreference>
</PreferenceScreen>
2. Create a Fragment extending PreferenceFragment. Do preference initialization and add OnSharedPreferenceChangeListener to update the UI when user input their name.
SettingsFragment.java:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// Preference Keys
public static final String KEY_PREF_NAME = "pref_key_name";
// Shared preference
SharedPreferences mSharedPreferences;
// Name preference
EditTextPreference mPreferenceName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Shared preference
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
// Name preference
mPreferenceName = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREF_NAME);
// Initialize
initPreferences();
}
public void initPreferences()
{
// Name
String oldName = mSharedPreferences.getString(KEY_PREF_NAME, "Enter your name here!");
// Update view
mPreferenceName.setSummary(oldName);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) {
if(key.equals(KEY_PREF_NAME))
{
// Name
String currentName = sharedPref.getString(key, "DEFAULT_VALUE");
// Update view
mPreferenceName.setSummary(currentName);
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
3. Finally, Create SettingsActivity and show SettingsFragment on its FrameLayout.
SettingsActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Settings Fragment
SettingsFragment settingsFragment = new SettingsFragment();
getFragmentManager().beginTransaction().replace(R.id.content, settingsFragment).commit();
}
#Override
protected void onResume() {
super.onResume();
}
}
HOW TO USE:
To use updated name from preference, get the name value from preference inside your activity or fragments onResume() method:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Name
String name = sharedPreferences.getString(SettingsFragment.KEY_PREF_NAME, "DEFAULT_VALUE");
// Do something with name
................
........................
}
}
OUTPUT:
Hope this will help~

Listening for SharedPreferences changes in MainActivity

I am trying to listen SharedPreferences changes in the MainActivity. And update the values in the settings of the app. And the working code goes like:
private SharedPreferences SP, prefs;
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Toast.makeText(MainActivity.this, "Key changed: "+key, Toast.LENGTH_SHORT).show();
}
};
SP.registerOnSharedPreferenceChangeListener(mListener);
But when I try to change the key value like this. It says can not resolve findPreference method. I tried doing it using context but still the error persists.
private SharedPreferences SP, prefs;
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("username")) {
Preference pref = findPreference(key);
pref.setDefaultValue(prefs.getString(key, "bob")); }
};
SP.registerOnSharedPreferenceChangeListener(mListener);
How can we import the method definition in MainActivity. Please tell if the way I am changing value here, if correct?
Settings.java
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.os.Bundle;
public class Settings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
PrefManager prefManager;
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference android:title="Your Name"
android:key="username"
android:summary="Please provide your username">
</EditTextPreference>
</PreferenceScreen>
I basically want to update the Preference in the settings page whenever SharedPreferences of key "username" is getting changed in the code.
You must implement PreferenceActivity in your activity
Add extends PreferenceActivity after your activity name and then import it's namespace:
public class MainActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
}
}
For more info look at http://developer.android.com/reference/android/preference/PreferenceActivity.html
EDITED
Use the following code:
public class Settings extends PreferenceActivity {
private SharedPreferences SP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
}
public static class MyPreferenceFragment extends PreferenceFragment implements
SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("username")) {
Preference pref = findPreference(key);
pref.setDefaultValue(prefs.getString(key, "bob"));
}
}
}
}

How to make the android main activity to 'reload' from outside?

I have an android main activity showing some data which are taken from the database. Now I have a PreferenceActivity which is shown when the user wants to change some preference, or delete the content of the database. But if this is the case, how do I force a 'reload' or something of the main activity from a class outside the main activity?
Set a OnSharedPreferenceChangeListener listener in your MainActivity to automatically detect any changes in the preferences.
SharedPreferencesListener
MainActivity.java
public class MainActivity extends ... {
private SharedPreferences settings;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Refresh display
refreshDisplay();
}
};
// Register the listener on the SharedPreferences
settings.registerOnSharedPreferenceChangeListener(listener);
// Other code
}
public void refreshDisplay() {
// Retrieve entries from sharedPreferences & display them, e.g
String prefValue1 = settings.getString("key1", "default value 1");
String prefValue2 = settings.getString("key2", "default value 2");
// Update UI with these values
}
}
EDIT:
Here is how your PreferenceActivity should be:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// R.xml.settings refers to the XML layout file named "settings"
// in your res/xml directory
addPreferencesFromResource(R.xml.settings);
}
}
If you just want to recharge an activity, you can do something like this:
finish();
startActivity(getIntent());

Updating dynamicaly summary preference with fragment?

I've got a problem with updating the summary value of a PreferncesFragment. I have tried to follow the advice of the post : Updating sharedPreferences Summary via listener but it doesn't work ! The summary doesn't update...
I don't understand what is wrong ? Thank's for your help !
My pref file :
<CheckBoxPreference
android:key="is_title"
android:summary="#string/conf_istitle_sum"
android:title="#string/conf_istitle_title"
android:defaultValue="true"
/>
<EditTextPreference
android:key="sms_title"
android:title="#string/conf_sms_title"
android:summary="#string/msgtitre"
android:dialogTitle="#string/conf_diagsms_title"
android:dialogMessage="#string/conf_diagsms_sum"
android:defaultValue="#string/msgtitre"
/>
My Preference class :
public class SetPreferenceActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
protected MyPreferenceFragment settingsFragment;
#Override
protected void onCreate(final Bundle savedInstanceState)
{ settingsFragment = new MyPreferenceFragment();
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
settingsFragment).commit();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("sms_title")) {
String newValue = sharedPreferences.getString(key, "");
settingsFragment.findPreference(key).setSummary(newValue);
}
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
What's working is the "old" solution deprecated OldPreferences
Please check whether onSharedPreferenceChanged is being called at all. You need to register the handler with your preferences. First,
get a reference to your preferences in onCreate:
public class SettingsActivity
extends AppCompatActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// ...
}
In the lifecycle of the Activity (note that I am using a plain AppCompatActivityrather than a PreferenceActiviy) register the handeler.
#Override
protected void onPause() {
super.onPause();
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
protected void onResume() {
super.onResume();
preferences.registerOnSharedPreferenceChangeListener(this);
}
Now, the handler should be called:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(DEBUG_TAG, key);
// fragment.findPreference(key) //... TBD
}

Categories

Resources