Android sharedpreferences Saving and Reading objects

Source: Internet
Author: User

Sharedpreferences Saving and Reading objects

1. First to serialize the object (below is an example of serializing the entity class, it is inconvenient to post all the code of the entity Class)

public class Loginresult extends Baseresult implements serializable{private static final long Serialversionuid = 1l;privat e String Mobiletoken;

2. Saving and reading the encapsulation of objects

public class Objectsaveutil {private final static string FILENAME = "Login_data_save";p rivate final static string KEY = "L  Oginresult "; /** * Desc: Save Object * @param context * @param key * @param obj to save objects, only objects that implement serializable are saved * Modified: */Pub Lic static void Saveobject (Context context,object obj) {try {//Save Object Sharedpreferences.editor Shar          Edata = 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 static object Reado          Bject (Context context) {try {sharedpreferences sharedata = context.getsharedpreferences (FILENAME, 0);               if (Sharedata.contains (key)) {string string = sharedata.getstring (Key, "");               if (Textutils.isempty (string)) {return null; }else{//Convert 16 binary data to 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.printstack      Trace ();      } 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: Convert 16 binary data to array * <p> Creator: Nie Xuyang, 2014-5-25 a.m. 11:08:33</p> * @param Data * @return * modifie      D: */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
Very useful, welcome to copy the use of


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android sharedpreferences Saving and Reading objects

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.