使用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);
到此這篇關於使用SharedPreferences
在Android存儲對象詳細代碼的文章就介紹到這瞭,更多相關使用SharedPreferences
在Android存儲對象內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Android SharedPreferences存取操作以及封裝詳解
- 如何使用GSON解析JSON數據
- Android文件存儲SharedPreferences源碼解析
- Android Gson基本用法學習
- Android數據存儲方式操作模式解析