安卓专题

使用SharedPreferences在Android存储对象

  为什么不用SQLite? 原因多种:除了面向对象和关系数据库之间的阻抗不匹配时,SQLite可能是矫枉过正(带来了更多的开销)对于一些简单的用例,或者其用法和语句可能会完全不喜欢。其他Android ORM 框架(ORMLite, greenDAO, Sugar ORM, ActiveAndroid, 等)或NOSQL移动数据库,如Couchbase精简版(Beta版在此时间)。 Couchbase精简版基本上是一个JSON数据库,它们旨在降低复杂性,但是同时又违背了抽象漏洞定律(所有不证自明的抽象都是有漏洞的)

 

代码如下:

/** 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();    
   }
   //...
}

其中User代码如下:

/** 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...
}

SharedPreferences看成一个Map存储,CRUD操作如下:

/** 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();
}

主键是通过getFieldKey方法, getFieldKey() 给我们每个用户每个字段的唯一标识。:

/** 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;
}

客户端调用如下:

// 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 是一个Java库,它提供了简单的toJSON()和fromJson()方法来转换Java对象到JSON格式,反之亦然。我们可以简单地存储JSON格式整个字符串到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);

 

 

 

猜你喜欢