这篇文章给大家介绍如何使用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
是一个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存储对象就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。