Android uses sharedpreferences to save objects

Source: Internet
Author: User

Core principle:

Serialization of objects

Steps

1. To save the object to implement serialization serializable

2. Save the serialized object as a string (the practice in this article is to save as a byte array in a string that is converted to 16 binary)

3. Deserializing a saved string into an object

Here is the complete code

Step 1. To save the object to implement serialization serializable

public class Sertest implements serializable{    private String name;    private int age;}
Step 2. Saves the serialized object as a string (the practice of this article is to save as a byte array in a string that is converted to 16 binary)

Step 3: Deserialize the saved string into an object

    /** * Desc: Save Object * @param context * @param key * @param obj object to save, save only objects that implement serializable * MoD            Ified: */public static void Saveobject (Context context,string key, Object obj) {try {//Save Object            Sharedpreferences.editor sharedata = context.getsharedpreferences (FILENAME, 0). Edit ();            First writes the serialized result to the byte cache, actually allocates one memory space Bytearrayoutputstream bos=new Bytearrayoutputstream ();            ObjectOutputStream os=new ObjectOutputStream (BOS);            Serializes an object to the byte cache Os.writeobject (obj);            Convert serialized data to 16 binary save String bytestohexstring = bytestohexstring (Bos.tobytearray ());            Save the 16 binary array sharedata.putstring (key, bytestohexstring);        Sharedata.commit ();            } catch (IOException e) {e.printstacktrace ();        LOG.E ("", "Save obj Failed"); }}/** * desc: Convert Array to 16 * @param Barray * @return * Modified: */public static StriNg bytestohexstring (byte[] barray) {if (Barray = = null) {return null;        } if (barray.length = = 0) {return "";        } stringbuffer sb = new StringBuffer (barray.length);        String stemp;            for (int i = 0; i < barray.length; i++) {stemp = integer.tohexstring (0xFF & Barray[i]);            if (Stemp.length () < 2) sb.append (0);        Sb.append (Stemp.touppercase ());    } return sb.tostring (); }/** * desc: Gets the Saved Object objects * @param context * @param key * @return * Modified: */Public OBJ ECT ReadObject (Context context,string key) {try {sharedpreferences sharedata = Context.getsharedprefer            Ences (FILENAME, 0);                 if (Sharedata.contains (key)) {string string = sharedata.getstring (Key, "");                 if (Textutils.isempty (string)) {return null; }else{//16 inData into an array, ready to deserialize byte[] Stringtobytes = Stringtobytes (string);                       Bytearrayinputstream bis=new Bytearrayinputstream (stringtobytes);                       ObjectInputStream is=new ObjectInputStream (bis);                       Returns the deserialized object readobject = Is.readobject ();                 return readobject; }}} catch (Streamcorruptedexception e) {//TODO auto-generated catch block e.pr        Intstacktrace ();        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();        } catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();            }//All exceptions return null return null;     }/** * desc: Converting 16 data into an array * <p> Creator: Nie Xuyang, 2014-5-25 a.m. 11:08:33</p> * @param Data * @return * Modified: * * public static byte[] StringtObytes (String data) {string Hexstring=data.touppercase (). Trim ();        if (Hexstring.length ()%2!=0) {return null;        } byte[] Retdata=new byte[hexstring.length ()/2];  for (int i=0;i

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: info-contact@alibabacloud.com 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.