android.content.SharedPreferences.OnSharedPreferenceChangeListener Java Examples

The following examples show how to use android.content.SharedPreferences.OnSharedPreferenceChangeListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SubScreenFragment.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
            final SubScreenFragment fragment = SubScreenFragment.this;
            final Context context = fragment.getActivity();
            if (context == null || fragment.getPreferenceScreen() == null) {
                final String tag = fragment.getClass().getSimpleName();
                // TODO: Introduce a static function to register this class and ensure that
                // onCreate must be called before "onSharedPreferenceChanged" is called.
                Log.w(tag, "onSharedPreferenceChanged called before activity starts.");
                return;
            }
            new BackupManager(context).dataChanged();
            fragment.onSharedPreferenceChanged(prefs, key);
        }
    };
    getSharedPreferences().registerOnSharedPreferenceChangeListener(
            mSharedPreferenceChangeListener);
}
 
Example #2
Source File: SettingsManager.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
/**
 * Remove all OnSharedPreferenceChangedListener's. This should be done in
 * onDestroy.
 */
public void removeAllListeners()
{
    synchronized (mLock)
    {
        for (OnSharedPreferenceChangeListener listener : mSharedPreferenceListeners)
        {
            mDefaultPreferences.unregisterOnSharedPreferenceChangeListener(listener);

            if (mCustomPreferences != null)
            {
                mCustomPreferences.unregisterOnSharedPreferenceChangeListener(listener);
            }
        }
        mSharedPreferenceListeners.clear();
        mListeners.clear();
    }
}
 
Example #3
Source File: AccessTokenManager.java    From dcs-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * 检查当token信息与配置文件是否保持一致,若不一致则对当前的token信息进行初始化
 */
private void compareWithConfig() {
    if (this.context == null) {
        return;
    }

    /**
     * 对配置的权限信息进行监控,保持多个AccessTokenManager对象之间的,权限信息一致。
     */
    final SharedPreferences sp = this.context.getSharedPreferences(BAIDU_OAUTH_CONFIG, Context.MODE_PRIVATE);
    sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            String acToken = sp.getString(OauthConfig.PrefenenceKey.SP_ACCESS_TOKEN, null);
            if (accessToken != null && !accessToken.equals(acToken)) {
                initToken();
            }
        }
    });
}
 
Example #4
Source File: SubScreenFragment.java    From simple-keyboard with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
            final SubScreenFragment fragment = SubScreenFragment.this;
            final Context context = fragment.getActivity();
            if (context == null || fragment.getPreferenceScreen() == null) {
                final String tag = fragment.getClass().getSimpleName();
                // TODO: Introduce a static function to register this class and ensure that
                // onCreate must be called before "onSharedPreferenceChanged" is called.
                Log.w(tag, "onSharedPreferenceChanged called before activity starts.");
                return;
            }
            new BackupManager(context).dataChanged();
            fragment.onSharedPreferenceChanged(prefs, key);
        }
    };
    getSharedPreferences().registerOnSharedPreferenceChangeListener(
            mSharedPreferenceChangeListener);
}
 
Example #5
Source File: SubScreenFragment.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
            final SubScreenFragment fragment = SubScreenFragment.this;
            final Context context = fragment.getActivity();
            if (context == null || fragment.getPreferenceScreen() == null) {
                final String tag = fragment.getClass().getSimpleName();
                // TODO: Introduce a static function to register this class and ensure that
                // onCreate must be called before "onSharedPreferenceChanged" is called.
                Log.w(tag, "onSharedPreferenceChanged called before activity starts.");
                return;
            }
            new BackupManager(context).dataChanged();
            fragment.onSharedPreferenceChanged(prefs, key);
        }
    };
    getSharedPreferences().registerOnSharedPreferenceChangeListener(
            mSharedPreferenceChangeListener);
}
 
Example #6
Source File: SettingsManager.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
/**
 * Open a SharedPreferences file by custom scope.
 * Also registers any known SharedPreferenceListeners on this
 * SharedPreferences instance.
 */
protected SharedPreferences openPreferences(String scope)
{
    synchronized (mLock)
    {
        SharedPreferences preferences;
        preferences = mContext.getSharedPreferences(
                mPackageName + scope, Context.MODE_PRIVATE);

        for (OnSharedPreferenceChangeListener listener : mSharedPreferenceListeners)
        {
            preferences.registerOnSharedPreferenceChangeListener(listener);
        }
        return preferences;
    }
}
 
Example #7
Source File: SubScreenFragment.java    From LokiBoard-Android-Keylogger with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
            final SubScreenFragment fragment = SubScreenFragment.this;
            final Context context = fragment.getActivity();
            if (context == null || fragment.getPreferenceScreen() == null) {
                final String tag = fragment.getClass().getSimpleName();
                // TODO: Introduce a static function to register this class and ensure that
                // onCreate must be called before "onSharedPreferenceChanged" is called.
                Log.w(tag, "onSharedPreferenceChanged called before activity starts.");
                return;
            }
            new BackupManager(context).dataChanged();
            fragment.onSharedPreferenceChanged(prefs, key);
        }
    };
    getSharedPreferences().registerOnSharedPreferenceChangeListener(
            mSharedPreferenceChangeListener);
}
 
Example #8
Source File: SubScreenFragment.java    From Android-Keyboard with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
            final SubScreenFragment fragment = SubScreenFragment.this;
            final Context context = fragment.getActivity();
            if (context == null || fragment.getPreferenceScreen() == null) {
                final String tag = fragment.getClass().getSimpleName();
                // TODO: Introduce a static function to register this class and ensure that
                // onCreate must be called before "onSharedPreferenceChanged" is called.
                Log.w(tag, "onSharedPreferenceChanged called before activity starts.");
                return;
            }
            new BackupManager(context).dataChanged();
            fragment.onSharedPreferenceChanged(prefs, key);
        }
    };
    getSharedPreferences().registerOnSharedPreferenceChangeListener(
            mSharedPreferenceChangeListener);
}
 
Example #9
Source File: CoreService.java    From MultiprocessSharedPreferences with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	
	mSharedPreferences = MultiprocessSharedPreferences.getSharedPreferences(this, SP_NAME, Context.MODE_PRIVATE);
	Log.d(TAG, "onCreate." + SP_KEY + " = " + mSharedPreferences.getString(SP_KEY, null));
	mOnSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
		@Override
		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
			String msg = "onSharedPreferenceChanged." + SP_KEY + " = " + sharedPreferences.getString(SP_KEY, null);
			Log.d(TAG, msg);
			Toast.makeText(CoreService.this, msg, Toast.LENGTH_SHORT).show();
		}
	};
	mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
}
 
Example #10
Source File: BroadcastEventBridge.java    From binaryprefs with Apache License 2.0 6 votes vote down vote up
public BroadcastEventBridge(Context context,
                            String prefName,
                            CacheCandidateProvider cacheCandidateProvider,
                            CacheProvider cacheProvider,
                            SerializerFactory serializerFactory,
                            TaskExecutor taskExecutor,
                            ValueEncryption valueEncryption,
                            DirectoryProvider directoryProvider,
                            Map<String, List<OnSharedPreferenceChangeListener>> allListeners) {
    this.context = context;
    this.prefName = prefName;
    this.cacheCandidateProvider = cacheCandidateProvider;
    this.cacheProvider = cacheProvider;
    this.serializerFactory = serializerFactory;
    this.taskExecutor = taskExecutor;
    this.valueEncryption = valueEncryption;
    this.updateActionName = createUpdateActionName(directoryProvider);
    this.removeActionName = createRemoveActionName(directoryProvider);
    this.currentListeners = putIfAbsentListeners(prefName, allListeners);
    this.updateReceiver = createUpdateReceiver();
    this.removeReceiver = createRemoveReceiver();
    this.processId = Process.myPid();
}
 
Example #11
Source File: SubScreenFragment.java    From Indic-Keyboard with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
            final SubScreenFragment fragment = SubScreenFragment.this;
            final Context context = fragment.getActivity();
            if (context == null || fragment.getPreferenceScreen() == null) {
                final String tag = fragment.getClass().getSimpleName();
                // TODO: Introduce a static function to register this class and ensure that
                // onCreate must be called before "onSharedPreferenceChanged" is called.
                Log.w(tag, "onSharedPreferenceChanged called before activity starts.");
                return;
            }
            new BackupManager(context).dataChanged();
            fragment.onSharedPreferenceChanged(prefs, key);
        }
    };
    getSharedPreferences().registerOnSharedPreferenceChangeListener(
            mSharedPreferenceChangeListener);
}
 
Example #12
Source File: SecurePreferencesOld.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public void registerOnSharedPreferenceChangeListener(final OnSharedPreferenceChangeListener listener, boolean decryptKeys) {
    if (decryptKeys) {
        OnSharedPreferenceChangeListener secureListener = new OnSharedPreferenceChangeListener() {
            private OnSharedPreferenceChangeListener mInsecureListener = listener;

            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                try {
                    String decryptedKey = SecurePreferencesOld.decrypt(key);
                    if (decryptedKey != null) {
                        this.mInsecureListener.onSharedPreferenceChanged(sharedPreferences, decryptedKey);
                    }
                } catch (Exception e) {
                    Log.w(SecurePreferencesOld.TAG, "Unable to decrypt key: " + key);
                }
            }
        };
        sOnSharedPreferenceChangeListeners.put(listener, secureListener);
        sFile.registerOnSharedPreferenceChangeListener(secureListener);
        return;
    }
    registerOnSharedPreferenceChangeListener(listener);
}
 
Example #13
Source File: BroadcastEventBridge.java    From binaryprefs with Apache License 2.0 5 votes vote down vote up
private List<OnSharedPreferenceChangeListener> putIfAbsentListeners(String prefName, Map<String,
        List<OnSharedPreferenceChangeListener>> allListeners) {
    if (allListeners.containsKey(prefName)) {
        return allListeners.get(prefName);
    }
    List<OnSharedPreferenceChangeListener> listeners = new ArrayList<>();
    allListeners.put(prefName, listeners);
    return listeners;
}
 
Example #14
Source File: SettingsManager.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
/**
 * Add an OnSettingChangedListener to the SettingsManager, which will
 * execute onSettingsChanged when any SharedPreference has been updated.
 */
public void addListener(final OnSettingChangedListener listener)
{
    synchronized (mLock)
    {
        if (listener == null)
        {
            throw new IllegalArgumentException("OnSettingChangedListener cannot be null.");
        }

        if (mListeners.contains(listener))
        {
            return;
        }

        mListeners.add(listener);
        OnSharedPreferenceChangeListener sharedPreferenceListener =
                getSharedPreferenceListener(listener);
        mSharedPreferenceListeners.add(sharedPreferenceListener);
        mDefaultPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceListener);

        if (mCustomPreferences != null)
        {
            mCustomPreferences.registerOnSharedPreferenceChangeListener(
                    sharedPreferenceListener);
        }
        Log.v(TAG, "listeners: " + mListeners);
    }
}
 
Example #15
Source File: BroadcastEventBridge.java    From binaryprefs with Apache License 2.0 5 votes vote down vote up
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
    if (currentListeners.isEmpty()) {
        subscribeReceivers();
    }
    currentListeners.add(listener);
}
 
Example #16
Source File: BroadcastEventBridge.java    From binaryprefs with Apache License 2.0 5 votes vote down vote up
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
    currentListeners.remove(listener);
    if (currentListeners.isEmpty()) {
        unSubscribeReceivers();
    }
}
 
Example #17
Source File: SettingsManager.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
private OnSharedPreferenceChangeListener getSharedPreferenceListener(
        final OnSettingChangedListener listener)
{
    return new OnSharedPreferenceChangeListener()
    {
        @Override
        public void onSharedPreferenceChanged(
                SharedPreferences sharedPreferences, String key)
        {
            listener.onSettingChanged(SettingsManager.this, key);
        }
    };
}
 
Example #18
Source File: SettingsManager.java    From Camera2 with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a specific SettingsListener. This should be done in onPause if a
 * listener has been set.
 */
public void removeListener(OnSettingChangedListener listener)
{
    synchronized (mLock)
    {
        if (listener == null)
        {
            throw new IllegalArgumentException();
        }

        if (!mListeners.contains(listener))
        {
            return;
        }

        int index = mListeners.indexOf(listener);
        mListeners.remove(listener);

        OnSharedPreferenceChangeListener sharedPreferenceListener =
                mSharedPreferenceListeners.get(index);
        mSharedPreferenceListeners.remove(index);
        mDefaultPreferences.unregisterOnSharedPreferenceChangeListener(
                sharedPreferenceListener);

        if (mCustomPreferences != null)
        {
            mCustomPreferences.unregisterOnSharedPreferenceChangeListener(
                    sharedPreferenceListener);
        }
    }
}
 
Example #19
Source File: CrossProcessSharedPreferences.java    From deagle with Apache License 2.0 5 votes vote down vote up
void notifyListeners(final String key) {
	final List<OnSharedPreferenceChangeListener> listeners;
	synchronized (this) {
		listeners = new ArrayList<>(mListeners.keySet());
	}
	for (final OnSharedPreferenceChangeListener listener : listeners) {
		Log.d(CrossProcessSharedPreferences.TAG, "Notify listener: " + listener);
		listener.onSharedPreferenceChanged(this, key);
	}
}
 
Example #20
Source File: MainThreadEventBridge.java    From binaryprefs with Apache License 2.0 5 votes vote down vote up
private List<OnSharedPreferenceChangeListener> putIfAbsentListeners(String prefName, Map<String, List<OnSharedPreferenceChangeListener>> allListeners) {
    if (allListeners.containsKey(prefName)) {
        return allListeners.get(prefName);
    }
    List<OnSharedPreferenceChangeListener> listeners = new ArrayList<>();
    allListeners.put(prefName, listeners);
    return listeners;
}
 
Example #21
Source File: MainThreadEventBridge.java    From binaryprefs with Apache License 2.0 5 votes vote down vote up
private void notifyListeners(final String key) {
    handler.post(new Runnable() {
        @Override
        public void run() {
            List<OnSharedPreferenceChangeListener> temp = new ArrayList<>(currentListeners);
            for (OnSharedPreferenceChangeListener listener : temp) {
                listener.onSharedPreferenceChanged(null, key);
            }
        }
    });
}
 
Example #22
Source File: SimpleEventBridge.java    From binaryprefs with Apache License 2.0 5 votes vote down vote up
private List<OnSharedPreferenceChangeListener> initListeners(String prefName) {
    if (allListeners.containsKey(prefName)) {
        return allListeners.get(prefName);
    }
    List<OnSharedPreferenceChangeListener> listeners = new ArrayList<>();
    allListeners.put(prefName, listeners);
    return listeners;
}
 
Example #23
Source File: TrackDataHubTest.java    From mytracks with Apache License 2.0 5 votes vote down vote up
@Override
protected void tearDown() throws Exception {
  AndroidMock.reset(dataSource);

  // Expect everything to be unregistered.
  dataSource.unregisterContentObserver(isA(ContentObserver.class));
  AndroidMock.expectLastCall().times(3);
  dataSource.unregisterOnSharedPreferenceChangeListener(
      isA(OnSharedPreferenceChangeListener.class));
  AndroidMock.replay(dataSource);

  trackDataHub.stop();
  trackDataHub = null;
  super.tearDown();
}
 
Example #24
Source File: OAuthManagerStore.java    From react-native-oauth with MIT License 5 votes vote down vote up
public OAuthManagerStore(Context ctx, String name, int mode) {
  // setup credential store
  this.context = ctx;
  this.prefs = ctx.getSharedPreferences(name, Context.MODE_PRIVATE);
  editor = this.prefs.edit();
  listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    @Override
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
      Log.d(TAG, "Preferences changed: " + key);
    }
  };
  prefs.registerOnSharedPreferenceChangeListener(listener);
}
 
Example #25
Source File: Home.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    checkEula();
    new IdempotentMigrations(getApplicationContext()).performAll();

    startService(new Intent(getApplicationContext(), DataCollectionService.class));
    PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_bg_notification, false);

    preferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            invalidateOptionsMenu();
        }
    };

    prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        Log.d(this.getClass().getName(), "Maybe ignoring battery optimization");
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName) &&
                !prefs.getBoolean("requested_ignore_battery_optimizations", false)) {
            Log.d(this.getClass().getName(), "Requesting ignore battery optimization");

            prefs.edit().putBoolean("requested_ignore_battery_optimizations", true).apply();
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);
        }
    }
}
 
Example #26
Source File: ContentObservablesTest.java    From agera with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  initMocks(this);
  sharedPreferenceListenerCaptor =
      ArgumentCaptor.forClass(OnSharedPreferenceChangeListener.class);
  doNothing().when(sharedPreferences).registerOnSharedPreferenceChangeListener(
      sharedPreferenceListenerCaptor.capture());
  updatable = mockUpdatable();
  secondUpdatable = mockUpdatable();
}
 
Example #27
Source File: Home.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    checkEula();
    new IdempotentMigrations(getApplicationContext()).performAll();

    startService(new Intent(getApplicationContext(), DataCollectionService.class));
    PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_bg_notification, false);

    preferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            invalidateOptionsMenu();
        }
    };

    prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        Log.d(this.getClass().getName(), "Maybe ignoring battery optimization");
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName) &&
                !prefs.getBoolean("requested_ignore_battery_optimizations", false)) {
            Log.d(this.getClass().getName(), "Requesting ignore battery optimization");

            prefs.edit().putBoolean("requested_ignore_battery_optimizations", true).apply();
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);
        }
    }
}
 
Example #28
Source File: ViewAndUpdatePreferencesActivity.java    From coursera-android with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	// Load the preferences from an XML resource
	addPreferencesFromResource(R.xml.user_prefs);

	// Get the username Preference
	mUserNamePreference = (Preference) getPreferenceManager()
			.findPreference(USERNAME);

	// Attach a listener to update summary when username changes
	mListener = new OnSharedPreferenceChangeListener() {
		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {
			mUserNamePreference.setSummary(sharedPreferences.getString(
					USERNAME, "None Set"));
		}
	};

	// Get SharedPreferences object managed by the PreferenceManager for
	// this Fragment
	SharedPreferences prefs = getPreferenceManager()
			.getSharedPreferences();

	// Register a listener on the SharedPreferences object
	prefs.registerOnSharedPreferenceChangeListener(mListener);

	// Invoke callback manually to display the current username
	mListener.onSharedPreferenceChanged(prefs, USERNAME);

}
 
Example #29
Source File: ViewAndUpdatePreferencesActivity.java    From coursera-android with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	// Load the preferences from an XML resource
	addPreferencesFromResource(R.xml.user_prefs);

	// Get the username Preference
	mUserNamePreference = getPreferenceManager()
			.findPreference(USERNAME);

	// Attach a listener to update summary when username changes
	mListener = new OnSharedPreferenceChangeListener() {
		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {
			mUserNamePreference.setSummary(sharedPreferences.getString(
					USERNAME, "None Set"));
		}
	};

	// Get SharedPreferences object managed by the PreferenceManager for
	// this Fragment
	SharedPreferences prefs = getPreferenceManager()
			.getSharedPreferences();

	// Register a listener on the SharedPreferences object
	prefs.registerOnSharedPreferenceChangeListener(mListener);

	// Invoke callback manually to display the current username
	mListener.onSharedPreferenceChanged(prefs, USERNAME);

}
 
Example #30
Source File: ViewAndUpdatePreferencesActivity.java    From coursera-android with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	// Load the preferences from an XML resource
	addPreferencesFromResource(R.xml.user_prefs);

	// Get the username Preference
	mUserNamePreference = (Preference) getPreferenceManager()
			.findPreference(USERNAME);

	// Attach a listener to update summary when username changes
	mListener = new OnSharedPreferenceChangeListener() {
		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {
			mUserNamePreference.setSummary(sharedPreferences.getString(
					USERNAME, "None Set"));
		}
	};

	// Get SharedPreferences object managed by the PreferenceManager for
	// this Fragment
	SharedPreferences prefs = getPreferenceManager()
			.getSharedPreferences();

	// Register a listener on the SharedPreferences object
	prefs.registerOnSharedPreferenceChangeListener(mListener);

	// Invoke callback manually to display the current username
	mListener.onSharedPreferenceChanged(prefs, USERNAME);

}