Sunday, May 27, 2012

Android: Using Preferences

Sometimes I find myself needing to cache certain little system status, such as if the user is currently logged in, what the logged in username/password are, etc. Using SQLiteHelper in this scenario is probably an overkill. This is when SharedPreferences comes in handy. In my app I implemented a simple Preferences class with the following definition: 



public final class Preferences {


/** 
* Configurable attributes. 

*/
public static final String LOGIN_USERNAME = "username";
public static final String LOGIN_PASSWORD = "password";
public static final String LOGIN_STATE = "loginState";


private static SharedPreferences pref;


private Preferences() {


}


static public void init(Context context) {


pref = context
.getSharedPreferences("PREF", Context.MODE_PRIVATE);
}


static public void setBoolean(String key, boolean value) {


pref.edit().putBoolean(key, value).commit();
}


static public boolean getBoolean(String key) {


return pref.getBoolean(key, false);
}


static public void setString(String key, String value) {


pref.edit().putString(key, value).commit();
}


static public String getString(String key) {


return pref.getString(key, null);
}
}


Since the function is implemented as a static class, one can simply call 


Preferences.setBoolean(Preferences.LOGIN_USERNAME, user); 


to set the variable anywhere else in the app. 

No comments:

Post a Comment