Android sharedpreferences Complex Storage

Source: Internet
Author: User

We know sharedpreferences simple types of data. Like what. String, int, and so on.

If you want to use sharedpreferences to access more complex data types (classes, images, etc.), you need to encode the data.

We typically convert data of complex types into Base64 encoding, and then store the converted data in an XML file as a string.

The BASE64 encoding and decoding library is not available in the Android SDK.

Therefore, you need to use a third-party jar package.

The

In this example uses the codec component in the Apache Commons component set for BASE64 encoding and decoding. The reader can download the installation package for the codec component from the address such as the following.

       The jar package (Commons-codec-1.4.jar) of the codec component is already included in the Lib subfolder of the Androidproject folder. As a result, 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 once the program executes again.

The following is the code for the Product class:

Java code:

Package Eoe.mobile;import java.io.serializable;//classes that need to be serialized 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); The mysharedpreferences is the sharedpreferences type variable defined in the class.

Before you 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 storing 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 you save, you need to select an image and display the image in the ImageView component, so. The image to be saved can be obtained directly from the ImageView component.

The code for storing 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 with the worst image effect and 100 being 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 preservation process.

This is to read the BASE64 format string from the XML file and decode it into a byte array. Finally, the byte array is converted 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 that loads 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 image to display the ImageView part in the method.

copyright notice: This article Bo Master original article. Blogs, without consent, may not be reproduced.

Android sharedpreferences Complex storage

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.