Usage Scenarios
In real-world development, it is often necessary to store objects, and the common idea is to use database-in-storage, but when you need to store only a small amount of data throughout your project, the database is a bit heavier. For example, the user information after successful login, in the whole project only this one data need to store, if because of this data storage use database for storage, whether it seems a bit overqualified, in fact, using sharedpreference to store user login information, is not a good choice , if you consider write and read efficiency problems at this time, you can do data persistence in memory.
Attention
The deposited object must be serialized (Serializable), otherwise it cannot be stored
For example, in the user object, it is necessary to serialize the user.
The sample code is as follows:
Public class User implements Serializable{ PrivateString name;PrivateString addr; PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringgetaddr() {returnAddr } Public void setaddr(String addr) { This. addr = addr; }@Override PublicStringtoString() {return "userinfo{"+"Name= '"+ name +' \ '+", addr= '"+ addr +' \ '+'} '; }}
Implementation code
1. Object storage
/** * Save information to sharedpreference <br> * * @param key * Type string key * @ param obj * Type Object */ Public void savetoshared(String key, Object obj) {Bytearrayoutputstream out =NewBytearrayoutputstream ();Try{ObjectOutputStream Oout =NewObjectOutputStream (out); Oout.writeobject (obj); String value =NewString (Base64.encode (Out.tobytearray ())); Editor editor = Sharedpreferences.edit (); Editor.putstring (Key,value); Editor.commit (); }Catch(IOException e) {E.printstacktrace (); } }
- Object Read
/** * Read the saved information from the sharedpreference <br> * * @param key * Read the key to save the message * @ return returns the Read information <br> * Type T <br> * Value for the Read content, type string, or null if key does not find the corresponding data */ PublicObjectQueryforsharedtoobject(String key) {String value = sharedpreferences.getstring (Key,NULL);if(Value! =NULL){byte[] valuebytes = Base64.decode (value); Bytearrayinputstream bin =NewBytearrayinputstream (valuebytes);Try{ObjectInputStream oin =NewObjectInputStream (BIN);returnOin.readobject (); }Catch(Exception e) {return NULL; } }return NULL; }
Package Sharedpreference Tool Class: Sharedpreference Tool Class
Using Sharedpreference for object storage