Well, I was a noob :
public final class AccessPreferences {
private static SharedPreferences prefs;
private static SharedPreferences getPrefs(Context ctx) {
SharedPreferences result = prefs;
if (result == null)
synchronized (AccessPreferences.class) {
result = prefs;
if (result == null) {
result = prefs = PreferenceManager
.getDefaultSharedPreferences(ctx);
}
}
return result;
}
public static <T> void put(final Context ctx, final String key,
final T value) {
final Editor ed = getPrefs(ctx).edit();
if (value == null) {
ed.putString(key, null); // this was called in testPutNullBoolean()
// **nulling** the boolean I put into prefs with testPutBoolean()
// - which run earlier (they run alphabetically (?) - not in the
// order they are declared anyway). So prefs.getString() found
// null and did not throw - whereas if I deleted testPutNullBoolean()
// it found a Boolean...
}
else if (value instanceof Boolean) ed.putBoolean(key, (Boolean) value);
//...
ed.commit();
}
//...
}
So what I was missing was that at my setUp()
the same ctx was returned :
//AccessPreferencesTest
static Context ctx;
@Override
protected void setUp() throws Exception {
super.setUp();
ctx = getContext(); // here
// ...
}
So just setting prefs to null was not enough - I had to explicitly clear them.
//AccessPreferencesTest
static SharedPreferences prefs; Editor e; // set up in setUp()
@Override
protected void setUp() throws Exception {
super.setUp();
ctx = getContext();
prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
e = prefs.edit();
}
@Override
protected void tearDown() throws Exception {
// Field f = AccessPreferences.class.getDeclaredField("prefs");
// f.setAccessible(true);
// // f.set(null, null); // NO USE
// final SharedPreferences sp = (SharedPreferences) f.get(null);
// if (sp != null) sp.edit().clear().commit();
// I only have to clear the preferences via an editor - the
// SharedPreferences are a singleton in the context of a single Context
// so no need to access them via AccessPreferences and no need to
// nullify the field in AccessPreferences [ie call f.set(null, null)] -
// as the reference to the singleton stays valid - apparently
if (ed != null) ed.clear().commit();
super.tearDown();
}
Would help if getContext()
stated clearly that the same ctx is returned - unfortunately there are no docs at all !