HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Wrapper around default shared preferences in Android

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
aroundpreferencessharedandroidwrapperdefault

Problem

Retrieving an instance of (Default) SharedPreferences and then calling the six methods that may be called to put/get a value gets pretty old pretty quickly, so I wrote this:

```
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public final class AccessPreferences {

private static final List> CLASSES = new ArrayList>();
static {
CLASSES.add(String.class);
CLASSES.add(Boolean.class);
CLASSES.add(Integer.class);
CLASSES.add(Long.class);
CLASSES.add(Float.class);
CLASSES.add(Set.class);
}

private AccessPreferences() {}

private static SharedPreferences prefs;

// TODO: do I need synchronized ? (1)
private static synchronized SharedPreferences getPrefs(Context ctx) {
if (prefs == null) {
prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
}
return prefs;
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // (5)
public static void persist(Context ctx, String key, T value) {
@SuppressLint("CommitPrefEdits")
final Editor ed = getPrefs(ctx).edit();
if (value == null) {
// commit it as that is exactly what the API does - can be retrieved
// as anything but if you give get() a default non null value it
// will give this default value back
ed.putString(key, null);
} else if (value instanceof String) ed.putString(key, (String) value);
else if (value instanceof Boolean) ed.putBoolean(key, (Boolean) value);
// TODO : IS THE ORDER OF FLOAT, INTEGER AND LONG CORRECT ? // (4)
else if (value instanceof Integer) ed.putInt(key, (Integer) value);
else if (v

Solution

I'm not too familiar with Android but I've found an issue with the code: both persist and retrieve methods contains the similar if-else chain. You should replace them with polymorphism:

  • Refactoring: Improving the Design of Existing Code by Martin Fowler: Replacing the Conditional Logic on Price Code with Polymorphism



  • Replace Conditional with Polymorphism



To answer some of your questions:

-
(4) The order is not important since there isn't any class (in Java, at least) which instanceof more than one of Long, Integer and Float.

-
(5) If it's invalid input data, I'd throw an exception with a detailed error message to the caller.

Context

StackExchange Code Review Q#28730, answer score: 4

Revisions (0)

No revisions yet.