Rather than hard-coding shared preference logic , create a Utility class like following and access it throughout your project. Separate methods are available for different data types
/**
* Shared preference class to handle app's local content
*/
public class SharedPreferenceHandler {
//Class variables
private SharedPreferences sharedPrefSettings;
private SharedPreferences.Editor editor;
private static SharedPreferenceHandler m_cPrefObj=null;
private SharedPreferenceHandler(Context context){
sharedPrefSettings = context.getSharedPreferences(SharedPreferenceConstants.SHARED_PREF_KEY, Context.MODE_PRIVATE);
editor=sharedPrefSettings.edit();
}
public static SharedPreferenceHandler getSharedPrefInstance(Context context){
if(m_cPrefObj==null){
m_cPrefObj=new SharedPreferenceHandler(context);
}
return m_cPrefObj;
}
/**
returns string value for shared preference key
*/
public String getSharedPrefValue(String key){
return sharedPrefSettings.getString(key,null);
}
/**
returns boolean shared preference value for key
*/
public boolean getSharedPrefValueBool(String key){
return sharedPrefSettings.getBoolean(key, false);
}
/**
sets string shared preference value for key
*/
public void setSharedPrefBool(String key,boolean value){
editor.putBoolean(key,value);
editor.commit();
}
/**
sets string shared preference value for key
*/
public void setSharedPref(String key,String value){
editor.putString(key, value);
editor.commit();
}
/**
*
* @param key
* @return
*/
public long getSharedPrefValueLong(String key){
return sharedPrefSettings.getLong(key,0);
}
/**
*
* @param key
* @param value
*/
public void setSharedPrefLong(String key,long value){
editor.putLong(key,value);
editor.commit();
}
/**
*
* @param key
* @return
*/
public int getSharedPrefValueInt(String key){
return sharedPrefSettings.getInt(key,0);
}
/**
*
* @param key
* @param value
*/
public void setSharedPrefInt(String key,int value){
editor.putInt(key,value);
editor.commit();
}
}
Inorder to access this logic in required classes,
private SharedPreferenceHandler mSharedPreferenceHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initiateDependencies();
}
/**
* Should initiate classes and objects which will be referred throughout app
*/
private void initiateDependencies(){
mSharedPreferenceHandler =SharedPreferenceHandler.getSharedPrefInstance(this);
}
To set shared preference value do the following
mSharedPreferenceHandler.setSharedPref("PREF_KEY_REFRESH_INTERVAL", "abc");
mSharedPreferenceHandler.setSharedPrefBool("PREF_KEY_REFRESH_ACTION",true);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…