Skip to content

Commit 01ed79c

Browse files
author
Christopher Tate
committed
Document immutable requirement of SharedPreferences return objects
In particular, make it quite clear that the set returned by getStringSet() must not be modfied by the app, period; and add a similar caution about the map returned via getAll(). Also, fix a bug that could lead to unexpected data being committed if the set instance passed to putStringSet() was mutated by the app after that call (including mutations after commit() was invoked). Bug 7312641 Change-Id: If9a1be1b0669ac879ff7a7dc67a8805548ea10cc
1 parent 69b0c97 commit 01ed79c

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

core/java/android/app/SharedPreferencesImpl.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,8 @@ public Editor putString(String key, String value) {
312312
}
313313
public Editor putStringSet(String key, Set<String> values) {
314314
synchronized (this) {
315-
mModified.put(key, values);
315+
mModified.put(key,
316+
(values == null) ? null : new HashSet<String>(values));
316317
return this;
317318
}
318319
}

core/java/android/content/SharedPreferences.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
* there is a single instance of this class that all clients share.
2626
* Modifications to the preferences must go through an {@link Editor} object
2727
* to ensure the preference values remain in a consistent state and control
28-
* when they are committed to storage.
28+
* when they are committed to storage. Objects that are returned from the
29+
* various <code>get</code> methods must be treated as immutable by the application.
2930
*
3031
* <p><em>Note: currently this class does not support use across multiple
3132
* processes. This will be added later.</em>
@@ -226,6 +227,10 @@ public interface Editor {
226227
/**
227228
* Retrieve all values from the preferences.
228229
*
230+
* <p>Note that you <em>must not</em> modify the collection returned
231+
* by this method, or alter any of its contents. The consistency of your
232+
* stored data is not guaranteed if you do.
233+
*
229234
* @return Returns a map containing a list of pairs key/value representing
230235
* the preferences.
231236
*
@@ -250,6 +255,10 @@ public interface Editor {
250255
/**
251256
* Retrieve a set of String values from the preferences.
252257
*
258+
* <p>Note that you <em>must not</em> modify the set instance returned
259+
* by this call. The consistency of the stored data is not guaranteed
260+
* if you do, nor is your ability to modify the instance at all.
261+
*
253262
* @param key The name of the preference to retrieve.
254263
* @param defValues Values to return if this preference does not exist.
255264
*

0 commit comments

Comments
 (0)