Sharedpreferences of Android Data storage

Source: Internet
Author: User
Tags gettext xml parser

I. Introduction of Sharedpreferences(1) sharedpreferences is a lightweight storage class on the Android platform that holds some of the most common configurations of the app, such as activity status, when activity is paused, Saves the state of this activity to sharedpereferences, and when the activity is overloaded, the system callback method Onsaveinstancestate, and then takes the value out of the sharedpreferences.  (2) Sharedpreferences provides the Java general Long, Int, string and other types of data storage interface. (3) Sharedpreferences is similar to the INI configuration file on a previous Windows system, but it is divided into multiple permissions and can be shared globally. (4) sharedpreferences is ultimately stored in XML, the overall efficiency is not particularly high, for the conventional lightweight is much better than SQLite, if the real storage can not consider their own definition of file format. XML processing is Dalvik through the native XML parser, such as the Xmlpull method, which is better for memory resource consumption. Second, examples(1) Layout file Main.xml
<?XML version= "1.0" encoding= "Utf-8"?><Tablelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"android:orientation= "vertical" >        <TableRow>        <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Name:"android:textsize= "20SP"/>        <EditTextAndroid:id= "@+id/name"Android:layout_width= "200DP"Android:layout_height= "Wrap_content"Android:text=""            />    </TableRow>     <TableRow>        <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Age:"android:textsize= "20SP"/>        <EditTextAndroid:id= "@+id/age"Android:layout_width= "200DP"Android:layout_height= "Wrap_content"Android:text=""            />    </TableRow>         <ButtonAndroid:id= "@+id/save"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Save"android:textsize= "20SP"         />     <ButtonAndroid:id= "@+id/show"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Display"android:textsize= "20SP"         />     <!--used to display data stored in sharedpreferences -    <TextViewAndroid:id= "@+id/result"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text=""android:textsize= "20SP"/></Tablelayout>

(2) Mainactivity.java in activity

 Packagecom.yby.sharedpreferences;Importandroid.app.Activity;ImportAndroid.content.Context;Importandroid.content.SharedPreferences;ImportAndroid.content.SharedPreferences.Editor;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateEditText Name,age; PrivateButton save,show; PrivateTextView result; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate); //Loading layout FilesSetcontentview (R.layout.main); //Initializing UI ControlsName =(EditText) Findviewbyid (r.id.name); Age=(EditText) Findviewbyid (r.id.age); Save=(Button) Findviewbyid (R.id.save); Show=(Button) Findviewbyid (r.id.show); Result=(TextView) Findviewbyid (R.id.result); //Monitor events for buttonsSave.setonclicklistener (listener);            Show.setonclicklistener (listener); }        PrivateOnclicklistener listener =NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method Stub//gets the Sharedpreferences object, and finally generates a Data.xml file
/**             *  sharedpreferences data Four modes of Operation                context.mode_private                context.mode_append                context.mode_ World_readable                context.mode_world_writeable                context.mode_private: For the default operation mode, which represents the file is private data and can only be accessed by the app itself, in that mode, The content written overwrites the contents of the original file                Context.mode_append: The schema checks whether the file exists, appends content to the file, or creates a new file.                Context.mode_world_readable and context.mode_world_writeable are used to control whether other apps have permission to read and write to the file.                Mode_world_readable: Indicates that the current file can be read by another application.                Mode_world_writeable: Indicates that the current file can be written by another application             */
Sharedpreferences preferences = mainactivity. This. Getsharedpreferences ("Data", context.mode_private); Switch(V.getid ()) { CaseR.id.save://Get Editor ObjectEditor Editor =Preferences.edit (); //Editor is a collection of maps, PUTXXX () to the inside of the plug value, Key-valueEditor.putstring ("name", Name.gettext (). toString ()); Editor.putint ("Age", Integer.parseint (Age.gettext (). toString ())); //a commit () must be executed at this point, otherwise the corresponding value cannot be obtained by GETXXX () .Editor.commit (); Toast.maketext (mainactivity. This, "Saved successfully", Toast.length_short). Show ();  Break;  Caser.id.show://GetXXX (PARAM1,PARAM2) The first parameter is the key when it is stored, and the second is a default value when the corresponding key is not found in the file .String name = preferences.getstring ("name", "null"); intAge = Preferences.getint ("Age", 0); //since I didn't give BIR this variable, this will show up as Bir is nullString bir = preferences.getstring ("Bir", "Bir is null"); //put the values stored in the sharedpreferences into the TextViewResult.settext ("Name:" +name+ ", Age:" +age+ ", Bir:" +bir);  Break; default:                 Break; }        }    };}

(3) Run the project to achieve the effect

  

(4) The data stored by Sharedpreferences is saved in the /data/data/package_name/shared_prefs directory, You can export an XML file from the Ddms in Eclipse, or you can view it in the form of a command

<?XML version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?><Map><stringname= "Name">Ffff</string><intname= "Age"value= " a" /></Map>

View by command

Sharedpreferences of Android Data 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.