Skip to content

Instantly share code, notes, and snippets.

@walterpalladino
Last active November 16, 2017 05:08
Show Gist options
  • Save walterpalladino/4f5509cbc8fc3ecf1497f05e37675111 to your computer and use it in GitHub Desktop.
Save walterpalladino/4f5509cbc8fc3ecf1497f05e37675111 to your computer and use it in GitHub Desktop.
Android Preferences Example
import android.content.Context;
import com.whp.android.SharedPreferencesDao;
import com.whp.android.serialization.SerializationUtils;
import java.io.IOException;
public class PersistenceManager {
/**
* Property Name : PREFERENCE_KEY
*
*/
public static final String PREFERENCE_KEY_SUFFIX = "preferences";
/**
* Property Name : PREFERENCE_GENERAL_SETTINGS
*
*/
public static final String PREFERENCE_GENERAL_SETTINGS = "PREFERENCE_GENERAL_SETTINGS";
/**
* getSettings
*
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static Settings getSettings(Context context) throws IOException, ClassNotFoundException {
SharedPreferencesDao preferences;
String tmp;
String preferencesKey = context.getPackageName () + "." + PREFERENCE_KEY_SUFFIX;
preferences = new SharedPreferencesDao (context, preferencesKey);
tmp = preferences.get (PREFERENCE_GENERAL_SETTINGS);
if ((tmp != null) && (!"".equals (tmp))) {
return (Settings) SerializationUtils.fromString (tmp);
} else {
return new Settings ();
}
}
/**
* setSettings
*
* @param settings
* @throws IOException
*/
public static void setSettings(Context context, Settings settings) throws IOException {
SharedPreferencesDao preferences;
String preferencesKey = context.getPackageName () + "." + PREFERENCE_KEY_SUFFIX;
preferences = new SharedPreferencesDao (context, preferencesKey);
if (settings != null) {
preferences.add (PREFERENCE_GENERAL_SETTINGS, SerializationUtils.toString (settings));
} else {
preferences.delete (PREFERENCE_GENERAL_SETTINGS);
}
}
}
private boolean getBooleanValue () {
// Get stored information about the game
Settings settings = null;
try {
settings = PersistenceManager.getSettings(this);
} catch (IOException e) {
// TODO : Ignore this, should not happen
e.printStackTrace ();
return false;
} catch (ClassNotFoundException e) {
// TODO : Ignore this, should not happen
e.printStackTrace ();
return false;
}
return settings.getBooleanValue();
}
import java.io.Serializable;
public class Settings implements Serializable {
private static final long serialVersionUID = -4079752511950172473L;
private Boolean booleanValue;
private Integer integerValue;
private String stringValue;
/**
* Constructor
*/
public Settings () {
this.booleanValue = false;
}
public Bool getBooleanValue () {
return booleanValue;
}
public void setBooleanValue (Boolean booleanValue) {
this.booleanValue = booleanValue;
}
// And so
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment