Android sharedpreferences Complex Storage

Source: Internet
Author: User

we know that sharedpreferences can only save simple types of data, such as String, int, and so on. If you want to use sharedpreferences to access more complex data types (classes, images, and so on), you need to encode the data. We typically convert data of complex types into Base64 encoding, and then save the transformed data as a string in an XML file.

the BASE64 encoding and decoding library is not available in the Android SDK. Therefore, you need to use a third-party jar package. In this example, the codec component in the Apache Commons component set is used for BASE64 encoding and decoding. The reader can download the installation package for the codec component from the following address.

The codec component's jar package (Commons-codec-1.4.jar) is already included in the Lib subdirectory of the Android engineering catalog, so readers can use the codec component directly in the project.

in this example, an object instance and an image of a product class are saved in an XML file, and the product objects and images are loaded from the XML file after the program is rerun. The following is the code for the Product class:

Java code:
Package Eoe.mobile;import java.io.serializable;//classes that require serialization must implement the Serializable interface public class Product implements Serializable{private string Id;private string name;private float price;<span style= "Font-family:microsoft Yahei, Tahoma, Simsun;color: #444444; " ><span style= "FONT-SIZE:14PX; font-weight:700; line-height:21px; " ></span></span>


before accessing the data, you need to create a Sharedpreferences object using the following code.

mysharedpreferences = getsharedpreferences ("base64", activity.mode_private); Where Mysharedpreferences is the sharedpreferences type variable defined in the class. Before you can save the product object, you need to create the Product object and assign the values in the corresponding component to the corresponding properties of the product class. The code for saving the Product object in an XML file is as follows:

Java code:

Product Product = new product ();p Roduct.setid (Etproductid.gettext (). toString ());p Roduct.setname ( Etproductname.gettext (). ToString ());p Roduct.setprice (Float.parsefloat (Etproductprice.gettext (). ToString ())); Bytearrayoutputstream BAOs = new Bytearrayoutputstream () objectoutputstream oos = new ObjectOutputStream (BAOs);// Place the Product object in OutputStream oos.writeobject (product), mysharedpreferences = Getsharedpreferences ("base64", activity.mode_private);//Convert the Product object to a byte array and encode it base64 string productBase64 = new String (Base64.encodebase64 ( Baos.tobytearray ())); Sharedpreferences.editor Editor = Mysharedpreferences.edit ();//writes the encoded string to the Base64.xml file editor.putstring ("Product", PRODUCTBASE64); Editor.commit ();


the method of saving an image is similar to the method of saving the Product object. Because before saving, you need to select an image and display the image in the ImageView component, so you can get the image you want to save directly from the ImageView component. The code to save the image in an XML file is as follows:

Java code:

Bytearrayoutputstream BAOs = new Bytearrayoutputstream ()//compress the image in the ImageView component into JPEG format, The compression results are saved in the Bytearrayoutputstream object ((bitmapdrawable) imageview.getdrawable ()). Getbitmap (). Compress ( Compressformat.jpeg, BAOs); String imageBase64 = new String (Base64.encodebase64 (Baos.tobytearray ()));//Save the BASE64 format string converted from the byte stream of the image editor.putstring ("Productimage", imageBase64); Editor.commit ();


the 2nd parameter of the Compress method represents the compression quality, with a range of 0 to 100,0 representing the highest compression ratio, but the image is the worst and 100 is the opposite. In this example, an intermediate value of 50 is taken.

loading product objects and images from an XML file is the inverse of the save process. This is to read the BASE64 format string from the XML file, decode it into a byte array, and finally convert the byte array into the product and Drawable objects. The code for loading the product object is as follows:

Java code:

String productBase64 = mysharedpreferences.getstring ("Product", "");//decoding a string in Base64 format byte[] base64bytes = Base64.decodebase64 (Productbase64.getbytes ()); Bytearrayinputstream Bais = new Bytearrayinputstream (base64bytes); ObjectInputStream ois = new ObjectInputStream (Bais) ;//Read the Product object from ObjectInputStream product Product = (product) ois.readobject (); <span style= "Font-family:microsoft Yahei, Tahoma, Simsun;color: #444444; " ><span style= "FONT-SIZE:14PX; font-weight:700; line-height:21px; " ></span></span>



the code for loading the image is as follows:

Java code:

String imageBase64 = mysharedpreferences.getstring ("Productimage", ""); base64bytes = Base64.decodebase64 ( Imagebase64.getbytes ()); Bais = new Bytearrayinputstream (base64bytes);// Display Image imageview.setimagedrawable (Drawable.createfromstream (Bais, "Product_image") on the ImageView component; <span style= " Font-family:microsoft Yahei, Tahoma, Simsun;color: #444444; " ><span style= "FONT-SIZE:14PX; font-weight:700; line-height:21px; " ></span></span>



         using the Createfromstream method of the Drawable class in the above code to create the Drawable object directly from the stream, and use the Setimagedrawable method to display the image on the ImageView component.

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.