Using Sharedpreference for object storage

Source: Internet
Author: User

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.


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.