I have an Android app with three different Activity
classes. Each of the Activities uses and changes config and user-customization data stored in a wrapped SharedPreference
s. The code could stand some refactoring, so I'm thinking that rather than have each Activity
instantiate the SharedPreference
s by calling PreferenceManager.getDefault...
in their constructors, I can make a 'base' abstract Activity to serve as a parent class and then have each of the Activities subclass the abstract Activity
and wrap the SharedPreference
s in an inner class of the abstract Activity
, like so:
public abstract class AbstractBaseActivity extends AppCompatActivity
{
private static AppPrefs instance;
private interface PrefKeys
{
String KEY_BOOL_SETUP = "KEY_BOOL_SETUP";
String KEY_STR_USER_EMAIL = "KEY_STR_USER_EMAIL";
String KEY_LONG_LAST_EMAIL_SENT = "KEY_LONG_LAST_USE";
//...remaining keys omitted...//
}
public static class AppPrefs implements PrefKeys
{
private SharedPreferences prefs;
private String no_email;
private AppPrefs(AbstractBaseActivity activity)
{
prefs = PreferenceManager.getDefaultSharedPreferences(activity);
no_email = activity.getString(R.string.no_email);
}
public static AppPrefs getInstance(AbstractBaseActivity activity)
{
if(instance == null)
{
instance = new AppPrefs(activity);
}
return instance;
}
public String getUserEmail()
{
return prefs.getString(AppPrefs.KEY_STR_USER_EMAIL, no_email);
}
public boolean setUserEmail(String email)
{
return prefs.edit().putString(AppPrefs.KEY_STR_USER_EMAIL, email).commit();
}
//... getter/setter methods to modify the SharedPreferences ...//
}
}
I like this approach because it simplifies getting the SharedPreference
s. I just call AppPrefs.getInstance(this)
from within the Activities or AppPrefs.getInstance(getActivity())
from within a Fragment
. Currently, my SharedPreferences
are wrapped in a custom Object
-- AppPrefs
-- which uses obviously named getter
s and setter
s to interact with my SharedPreference
data without actually having to muck about with key-value pairs and remembering to call commit()
when changing data, but it is a stand-alone class. It seems to make sense to make the AppPrefs
class an inner class of the AbstractBaseActivity
class, but I'd welcome any criticisms of the approach.
I'm also uncertain about how I'm dealing with getting the AppPrefs
object -- is there a better way to implement instantiation?
What are the downsides I'm not seeing?