Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shared preference manager
package com.matie.redgram.data.managers.preferences.main;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by matie on 20/09/15.
*
* Singleton manager
*/
public class PreferenceManager {
private static Context mContext;
public PreferenceManager(Context context){
mContext = context;
}
/**
* Obtains a specified preference by passing a key.
* @param key
* @return The specified preference
*/
public SharedPreferences getSharedPreferences(String key){
return mContext.getSharedPreferences(key, mContext.MODE_PRIVATE);
}
/**
*
* @param prefs
* @param key
* @param value
*/
public void setString(SharedPreferences prefs, String key, String value){
prefs.edit().putString(key, value).commit();
}
/**
*
* @param prefs
* @param key
* @param defaultValue
* @return Returns the string paired with the key, or the defaultValue if nothing is returned.
*/
public String getString(SharedPreferences prefs, String key, String defaultValue){
return prefs.getString(key, defaultValue);
}
/**
*
* @param prefs
* @param key
*/
public void remove(SharedPreferences prefs, String key){
prefs.edit().remove(key).commit();
}
/**
*
* @param prefs
* @return
*/
public boolean clear(SharedPreferences prefs){
return prefs.edit().clear().commit();
}
}
@shaybarak

This comment has been minimized.

Copy link

shaybarak commented Sep 21, 2015

If you're caching a Context in a static field, at least make sure to cache the application Context.
mContext = context.getApplicationContext();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.