Android SharedPreferences complex storage, androidshared

Source: Internet
Author: User

Android SharedPreferences complex storage, androidshared
We know that SharedPreferences can only store simple types of data, such as String and int. If you want to use SharedPreferences to access more complex data types (such as classes and images), you need to encode the data. We usually convert complex types of data into Base64 encoding, and then save the converted data in the XML file as strings.

The Android SDK does not provide Base64 encoding and decoding libraries. Therefore, a third-party jar package is required. In this example, the Codec component in the Apache Commons component is used for Base64 encoding and decoding. You can download the installation package of the Codec component from the address below.

The lib subdirectory of the Android project directory contains the jar package (commons-codec-1.4.jar) of the Codec component, so that readers can directly use the Codec component in the project.

In this example, an object instance of the Product class and an image are stored in the XML file, and the Product object and image are loaded from the XML file after the program re-runs. The following is the code of the Product class:

Java code:

Package eoe. mobile; import java. io. serializable; // the class 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>


Before accessing data, you must use the following code to create a SharedPreferences object.

MySharedPreferences = getSharedPreferences ("base64", Activity. MODE_PRIVATE); mySharedPreferences is the SharedPreferences type variable defined in the class. Before saving the Product object, you must create a 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 (); product. setId (etProductID. getText (). toString (); product. setName (etProductName. getText (). toString (); product. setPrice (Float. parseFloat (etProductPrice. getText (). toString (); ByteArrayOutputStream baos = new ByteArrayOutputStream (); ObjectOutputStream oos = new ObjectOutputStream (baos); // put 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 with base64 String productBase64 = new String (Base64.encodeBase64 (baos. toByteArray (); SharedPreferences. editor editor = mySharedPreferences. edit (); // write the encoded string to the editor in the base64.xml file. putString ("product", productBase64); editor. commit ();


The method for saving images is similar to that for saving Product objects. Because you need to select an image before saving and display the image in the ImageView component, you can directly obtain the image to save from the ImageView component. The code for saving an image in an XML file is as follows:

Java code:

ByteArrayOutputStream baos = new ByteArrayOutputStream (); // compress the image in the ImageView component into JPEG format, and save the compression result in ByteArrayOutputStream (BitmapDrawable) imageView. getDrawable ()). getBitmap (). compress (CompressFormat. JPEG, 50, baos); String imageBase64 = new String (Base64.encodeBase64 (baos. toByteArray (); // Save the Base64 Format String editor that is converted from the byte stream of the image. putString ("productImage", imageBase64); editor. commit ();


Among them, the compress method uses 2nd parameters to indicate the compression quality. The value ranges from 0 to 100. 0 indicates the highest compression ratio, but the image has the worst effect, and indicates the opposite. In this example, an intermediate value of 50 is obtained.

Load the Product object and image in the XML file. That is, to read strings in Base64 format from the XML file, then decode them into byte arrays, and finally convert the byte arrays into Product and Drawable objects. The code for loading the Product object is as follows:

Java code:

String productBase64 = mySharedPreferences. getString ("product", ""); // decodes byte [] base64Bytes = bytes (productBase64.getBytes (); ByteArrayInputStream bais = new ByteArrayInputStream (base64Bytes ); objectInputStream ois = new ObjectInputStream (bais); // read the Product object Product = (product) ois from ObjectInputStream. readObject (); <span style = "font-family: Microsoft Yahei, Tahoma, Simsun; color: #444444;"> <span style = "font-size: 14px; font-weight: 700; line-height: 21px; "> </span>



The code for loading images is as follows:

Java code:

String imageBase64 = mySharedPreferences. getString ("productImage", ""); base64Bytes = Base64.decodeBase64 (imageBase64.getBytes (); bais = new ByteArrayInputStream (base64Bytes); // display the image ImageView on the imageView component. setImageDrawable (Drawable. createFromStream (bais, "product_image"); <span style = "font-family: Microsoft Yahei, Tahoma, Simsun; color: #444444; "> <span style =" font-size: 14px; font-weight: 700; line-height: 21px; "> </span>



In the above Code, the createFromStream method of the Drawable class is used to directly create a Drawable object from the stream, and the setImageDrawable method is used to display the image on the ImageView component.
For the storage of sharedpreferences in Android, the source code is as follows:

Share. edit (). remove ("number" + arg2). remove ("name" + arg2). commit ();
Listitem. revome (arg2 );
ListItemAdapter. policydatasetchanged ();

Add these sentences to onItemClickListener.

Also, do not remember whether SimpleAdapter directly uses the rmove method. If so, you do not need to call yydatasetchanged ();

How does Android SharedPreferences store data in one activity? How does one obtain the SharedPreferences data in another activity?

This is not difficult to implement. In another activity, call this. getSharedPreferences ('your sharedPreference name' int mode;

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.