Skip to content

Instantly share code, notes, and snippets.

@mhdatie
Created September 20, 2015 21:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhdatie/0e76e77b41edce30891d to your computer and use it in GitHub Desktop.
Save mhdatie/0e76e77b41edce30891d to your computer and use it in GitHub Desktop.
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
Copy link

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