Using SharedPreferences to store object detail code in Android
- 2021-12-21 05:14:38
- OfStack
Why not
SQLite
? There are a number of reasons: SQLite may be overkill (incurring more overhead) except for impedance mismatches between object-oriented and relational databases for a simple use case, or its usage and statements may be totally disliked. Others
Android ORM
Framework (ORMLite, greenDAO, Sugar, ORM, ActiveAndroid, etc.) or
NOSQL
Move databases, such as
Couchbase
Simplified version (Beta version at this time). Couchbase is basically an JSON database designed to reduce complexity, but at the same time violates the Law of Abstraction Vulnerability (all self-evident abstractions are vulnerable)
The code is as follows:
/** stores the user object in SharedPreferences */
public class UserPrefs{
/** This application's preferences label */
private static final String PREFS_NAME = "com.our.package.UserPrefs";
/** This application's preferences */
private static SharedPreferences settings;
/** This application's settings editor*/
private static SharedPreferences.Editor editor;
/** Constructor takes an android.content.Context argument*/
public UserPrefs(Context ctx){
if(settings == null){
settings = ctx.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE );
}
/*
* Get a SharedPreferences editor instance.
* SharedPreferences ensures that updates are atomic
* and non-concurrent
*/
editor = settings.edit();
}
//...
}
Where the User code is as follows:
/** User object to be saved in db */
public class User{
private int id; // used for object storage
private String userName;
private boolean registered;
private double score;
/** Constructor */
public User(int id, String userName, boolean registered, double score){
this.id = id;
this.userName = userName;
this.registered = registered;
this.score = score;
}
// getters and setters here...
}
Will
SharedPreferences
As an Map store,
CRUD operates as follows:
/** generic field keys */
private static final String KEY_USERNAME = "com.our.package.KEY_USERNAME";
private static final String KEY_REGISTERED = "com.our.package.KEY_REGISTERED";
private static final String KEY_SCORE = "com.our.package.KEY_SCORE";
/** Store or Update */
public void setUser(User user){
if(user == null)
return; // don't bother
int id = user.getId();
editor.putString(
getFieldKey(id, KEY_USERNAME),
user.getUsername() );
editor.putBoolean(
getFieldKey(id, KEY_REGISTERED),
user.isRegistered() );
editor.putFloat(
getFieldKey(id, KEY_SCORE),
user.getScore() );
editor.commit();
}
/** Retrieve */
public User getUser(int id){
String name = settings.getString(
getFieldKey(id, KEY_USERNAME),
"" ); // default value
boolean registered = settings.getBoolean(
getFieldKey(id, KEY_REGISTERED),
false); // default value
double score = settings.getFloat(
getFieldKey(id, KEY_SCORE),
0); // default value
return new User(id, name, registered, score);
}
/** Delete */
public void deleteUser(User user){
if(user == null)
return; // don't bother
int id = user.getId();
editor.remove( getFieldKey(id, KEY_USERNAME) );
editor.remove( getFieldKey(id, KEY_REGISTERED) );
editor.remove( getFieldKey(id, KEY_SCORE) );
editor.commit();
}
The primary key is passed through the
getFieldKey
Method,
getFieldKey()
Give us the only 1 identification of each field for each user.
/** The prefix for flattened user keys */
public static final String KEY_PREFIX =
"com.our.package.KEY";
/** Method to return a unique key for any field belonging to a given object
* @param id of the object
* @param fieldKey of a particular field belonging to that object
* @return key String uniquely identifying the object's field
*/
private String getFieldKey(int id, String fieldKey) {
return KEY_PREFIX + id + "_" + fieldKey;
}
Client calls are as follows:
// get a SharedPreferences instance
UserPrefs prefs = new UserPrefs( this.getApplicationContext() );
// get id from server or local storage
// then find User with that id
User user = prefs.getUser(id);
// operations on User, e.g.
user.setRegistered(true);
user.setScore(new_score);
// save
prefs.setUser(user);
// ...or delete
prefs.deleteUser(user),
Gson
Gson
Is one
Java
Library, which provides a simple
toJSON()
And
Android ORM
0
Method to convert
Java
Object to
JSON
Format, and vice versa. We can simply store
JSON
Format the entire string to
SharedPreferences
:
// convert User object user to JSON format
Gson gson = new Gson();
String user_json = gson.toJson(user);
// store in SharedPreferences
String id = "" + user.getId(); // get storage key
editor.putString(id, user_json);
editor.commit();
// time flies...
// do the reverse operation
user_json = settings.getString(id, "");
user = gson.fromJson(user_json, User.class);