Android SharedPreferences stores complex objects

Source: Internet
Author: User

It is convenient to use SharedPreferences to store some common settings. However, we know that SharedPreferences can only store some simple types. How can we use SharedPreferences to store some complex objects? The following uses map as an example to see how SharedPreferences stores complex objects. If you want to use SharedPreferences to access complex data types, you need to encode the data. Data is usually converted to Base64 encoding, And the converted data is stored as strings. Storage: [java] // converts a map to byte [] ByteArrayOutputStream toByte = new ByteArrayOutputStream (); ObjectOutputStream oos = new ObjectOutputStream (toByte); oos. writeObject (map); // encode byte [] In Base64 String payCityMapBase64 = new String (Base64Coder. encode (toByte. toByteArray (); // stores the editor. putString (KEY_CITY, payCityMapBase64); editor. commit (); // convert map to byte [] ByteArrayOutputStream toByte = new ByteArrayOutputStream (); ObjectOutputStream oos = new ObjectOutputStream (toByte); oos. writeObject (map); // encode byte [] In Base64 String payCityMapBase64 = new String (Base64Coder. encode (toByte. toByteArray (); // stores the editor. putString (KEY_CITY, payCityMapBase64); editor. commit (); The following is read: [java] byte [] base64Bytes = Base64Coder. decode (prefer. getString (KEY_CITY, null); ByteArrayInputStream bais = new ByteArrayInputStream (base64Bytes); ObjectInputStream ois = new ObjectInputStream (bais); map = (Map) ois. readObject (); boolean B = (Boolean) map. get (cityId); byte [] base64Bytes = Base64Coder. decode (prefer. getString (KEY_CITY, null); ByteArrayInputStream bais = new ByteArrayInputStream (base64Bytes); ObjectInputStream ois = new ObjectInputStream (bais); map = (Map) ois. readObject (); boolean B = (Boolean) map. get (cityId );

Related Article

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.