How to store data using Sharedpreferences classes in Android applications _android

Source: Internet
Author: User
Tags constant

There are a variety of storage technologies available in the Android system. These storage technologies allow you to store data on a variety of storage media. For example, sharedpreferences can store 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 databases, and content Provider. Here we will introduce the way of sharedpreferences storage.

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

Sharedpreferences is a way to store application configuration information as a key value pair, and it can store only basic data types. A program's configuration file can only be used in this application, or only 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 the/data/data//shares_prefs in Ddms in File Explorer.

Sharedpreferences technology is the easiest to understand and use in all of the Android SDK Storage technologies because sharedpreferences is dealing with a key–value pair. For example, to save the name of the product, you can set the key to Producename,value as the actual product name.

First, the method of obtaining the Sharedpreferences object

(1) through function context.getsharedpreferences (String name,int mode), where name is the profile name of this component (if you want to share this profile with other components of this application, You can use this name to retrieve this profile), mode is the operating mode, the default mode is 0 or mode_private, and 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 mode of operation, the default pattern is 0 or mode_private; The return value is sharedpreferences.

Second, use sharedpreferences Access data

Save Key-value You typically specify a filename, and then specify key and value in a similar putstring method. The same method is used by sharedpreferences. The steps to save Key-value with Sharedpreferences are as follows:

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

(2) using the Sharedpreferences interface edit to obtain the Sharedpreferences.editor object.

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

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

III. storage location and format of data

Sharedpreferences writes the data file in a private directory on the phone's memory. The test program in the emulator can view the location of the data file through the ADT Ddms perspective.

Iv. save more complex types of data

The sharedpreferences described earlier can only save simple types of data, 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.

V. Setting access rights for data files

Because Android is not a completely innovative operating system, but a mobile operating system developed on the Linux kernel, Android has some basic features of Linux. We use the Getsharedpreferences method to get the Sharedpreferences object, and the 2nd parameter value of the Getsharedpreferences method uses the Activity.mode_private constant. There are 3 other constants that can be used in addition to this constant. These 4 constants are used to specify the mode in which files are established. One of their important functions is to set the properties of the file so that you can set the access rights for the data file.

Six, can save the set of 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 to transparently save configuration information. This is preferenceactivity.

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

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

Checkboxpreference: Corresponding label. The setup item creates a CheckBox component.
Edittextpreference: Corresponding label. Clicking the settings item pops up a dialog box with the EditText component.
Listpreference: Corresponding label. Clicking it pops up a dialog box with the ListView component.


sample
First figure:

And then the Main.xml.

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:orientation=" vertical " 
  android:layout_width=" fill_parent " 
  android:layout_" height= "Fill_parent" 
  > 
<textview  
  android:layout_width= "fill_parent"  
  android:layout_ height= "Wrap_content"  
  android:id= "@+id/textview" 
  /> 
</LinearLayout> 

The code for the activity:

Package cn.com.sharedPreferencesTest; 
Import android.app.Activity; 
Import android.content.SharedPreferences; 
Import Android.os.Bundle; 
Import Android.util.Log; 
 
Import Android.widget.TextView; public class Sharedpreferencesactivity extends activity {@Override public void onCreate (Bundle savedinstancestate) 
    {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    Savesharedpreferences (); 
     
  Readsharedpreferences (); /** * @description Create and save some settings information/private void savesharedpreferences () {/* * Getsharedprefe The rences (String name,int mode) method is an abstract method defined in the context, implemented in Contextwrapper, * 
     The method creates a Sharedpreferences object to return based on the name and write type passed by the user. * In activity, there is also a way to go back to sharedpreferences objects, this method is sharedpreferences sharedpreferences = getpreferences (mode_private 
     ); * The change method is defined and implemented in the activity, there is no Name parameter because the method defaults to the name attribute of the class name of the current activity (the class names here do not include the package path) */Sharedpreferences Sharedprefe Rences = GetsharedpreferenCES ("preferences", mode_private); 
    Storage data Sharedpreferences.editor Editor = Sharedpreferences.edit (); 
    Editor.putstring ("name", "Jolin Tsai"); 
    Editor.putint ("Age", 31); 
     
    Boolean B = Editor.commit (); if (b) {log.i ("Notice:", "Save success!") 
    "); }else{log.i ("Notify", "Save failed!") 
    "); }/** * @author Chenzheng_java * @description Read the data we added to the Sharedpreference object * @since 2011/03 
    /05 * * private void Readsharedpreferences () {String result = "Beauty info:/n"; 
    Sharedpreferences sharedpreferences = this.getsharedpreferences ("preferences", mode_private); 
    result+= "Name" +sharedpreferences.getstring ("name", "No person for the time being"); 
    result+= "Age" +sharedpreferences.getint ("Aged",-1); 
    TextView TextView = (TextView) Findviewbyid (R.id.textview); 
     
  Textview.settext (result); 

 } 
   
   
}

The rest is the default.

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.