Android's mobile storage sharedpreferences

Source: Internet
Author: User

A variety of storage technologies are available in the Android system. These storage technologies enable you to store data on a variety of storage media. For example, Sharedpreferences can store the data in the private storage area of the application software. The data for these stores can only be read by the software that writes the data. Of course, Android also supports file storage, SQLite database, and content Provider. Here we will introduce the Sharedpreferences storage method.

Sharedpreferences is a lightweight way of storing data, and students who have learned web development can imagine it as a small cookie. It can store simple data types (boolean, int, float, long, and string) in the same way as key-value pairs in the application's private directory (data/data/package name/shared_prefs/) in its own defined XML file.

Sharedpreferences is a way to store configuration information for an application in key-value pairs, which can only store basic data types. A program's configuration file can only be used in this application, or can only be used within the same package, and cannot be used between different packages. In fact, sharedpreferences is using XML format to store data in the device, under/data/data//shares_prefs in the File Explorer in Ddms.

first, the method of obtaining the Sharedpreferences object

(1) through the function context.getsharedpreferences (String name,int mode), where name is the configuration file name of this component (if you want to share this profile with other components of the application, This name can be used to retrieve the configuration file), mode is the operating mode, the default mode is 0 or mode_private; The return value is sharedpreferences.

(2) through the function activity.getpreferences (int mode), where the configuration file can only be used by the invoked activity. Mode is the operation, the default mode is 0 or mode_private; The return value is sharedpreferences.

Second, using Sharedpreferences Access data

Save Key-value to typically specify a file name, and then specify key and value in a way similar to putstring. Sharedpreferences also uses the same approach. The steps to save the Key-value pair using Sharedpreferences are as follows:

(1) Use the Activity class's Getsharedpreferences method to obtain the Sharedpreferences object. The name of the file name where the key-value is stored is specified by the first parameter of the Getsharedpreferences method.

(2) Use edit of Sharedpreferences interface to get Sharedpreferences.editor object.

(3) The Putxxx method of Sharedpreferences.editor interface is used to save the key-value pair. where xxx represents the different data types of value. The value of the Boolean type is the Putboolean method, and the string type is the Putstring method.

(4) The Key-value pair is saved by the commit method of the Sharedpreferences.editor interface. The Commit method is equivalent to a commit operation in a database transaction. The data is actually saved in the database only if it is committed after the event has ended. The same is true for saving key-value.

Third, the location and format of data storage

Sharedpreferences writes the data file in a directory that is private to the phone's memory. In the simulator, the test program can view the location of the data file through the DDMS perspective of ADT.

Iv. preservation of more complex types of data

The sharedpreferences described earlier can only hold data of a simple type, such as String,int. If you need to access more complex data types such as classes or images, you need to encode the data, usually convert it to BASE64 encoding, and then save the converted data as a string in the XML file.

Sharedpreferences Save List Collection

 Public StaticString weatherlist2string (list<weather>weatherlist)throwsIOException {//instantiates a Bytearrayoutputstream object that is used to mount the compressed byte file. Bytearrayoutputstream Bytearrayoutputstream =NewBytearrayoutputstream (); //The resulting character data is then loaded into the ObjectOutputStreamObjectOutputStream ObjectOutputStream =NewObjectOutputStream (Bytearrayoutputstream); //The WriteObject method is responsible for writing the state of an object of a particular class so that the appropriate ReadObject method can restore itObjectoutputstream.writeobject (weatherlist); //Finally, convert the byte file to Base64 encoding with Base64.encode in stringString weatherliststring =NewString (Base64.encode (Bytearrayoutputstream.tobytearray (), Base64.default)); //Close ObjectOutputStreamObjectoutputstream.close (); returnweatherliststring; } @SuppressWarnings ("Unchecked")     Public StaticList<weather>string2weatherlist (String weatherliststring)throwsstreamcorruptedexception, IOException, classnotfoundexception {byte[] Mobilebytes =Base64.decode (Weatherliststring.getbytes (), base64.default); Bytearrayinputstream Bytearrayinputstream=NewBytearrayinputstream (mobilebytes); ObjectInputStream ObjectInputStream=NewObjectInputStream (Bytearrayinputstream); List<Weather> weatherlist = (list<weather>) ObjectInputStream. ReadObject ();        Objectinputstream.close (); returnweatherlist; }

Sharedpreferences saving pictures and serializable objects

View Code

V. Setting access rights for data files

Because Android is not a completely innovative operating system, but a mobile operating system developed on the basis of the Linux kernel, Android has some basic features of Linux. We get the Sharedpreferences object using the Getsharedpreferences method, and the 2nd parameter value of the Getsharedpreferences method uses the Activity.mode_private constant. In addition to this constant, you can use an additional 3 constants. These 4 constants are used to specify the file's build pattern. One of their important functions is to set the properties of the file, so that you can set the access permissions for the data file.

Six, can save the settings of the activity:preferenceactivity

Because Sharedpreferences can easily save Key-value pairs, it is common to use Sharedpreferences to save configuration information. However, the Android SDK provides an easier way to design the configuration interface and can transparently save configuration information. This is preferenceactivity.

Preferenceactivity is a subclass of activity, which encapsulates the sharedpreferences. Therefore, all preferenceactivity subclasses have the ability to save key-value pairs.

Preferenceactivity provides a number of common settings items that can meet the requirements of most configuration interfaces. As with components, these configuration items can be created from either an XML file or from code. The more commonly used are:

    • Checkboxpreference: the corresponding label. The setting item creates a CheckBox component.
    • Edittextpreference: the corresponding label. Clicking the setting item pops up a dialog box with the EditText component.
    • Listpreference: the corresponding label. Clicking the setting item pops up a dialog box with the ListView component.

Http://www.cnblogs.com/zyw-205520/archive/2013/04/09/3010912.html

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.