35th: Sharedpreferences of Android data storage

Source: Internet
Author: User

People's life, always inevitably have ups and downs. Will not always be like sunrise, nor will never be miserable. Repeatedly to float a sinking, for a person, it is honed. Therefore, the floating above, do not have to be proud; Must be frank, humble attitude, optimistic and enterprising, moving forward. --Panasonic's Help


This content: Sharedpreferences data storage

First,the role of Sharedpreferences

When the application is running, it may keep the user's configuration information as the user uses it, such as the EQ settings at the last playback, the volume settings, and so on, which can be maintained by Sharedpreferences. The data persisted by Sharedpreferences is an XML file that is located in the application's private folder. the saved data is primarily a simple type of key-value pair (Key-value)


Second, sharedpreferences is an interface, the program is unable to create sharedpreferences instances, can be context.getsharedpreferences (String name.int mode) to get a sharedpreferences instance

Name: Refers to the file name, does not need to add the suffix. XML, the system will be added to us automatically. Generally this file is stored under /data/data/<package name>/shared_prefs (often asked in this interview)

Mode: is the specified read and write mode, the value of three kinds, respectively:

context.mode_private: Specifies that the sharedpreferences data can only be read and written by this application

context.mode_world_readable: Specifies that the sharedpreferences data can be read by other applications but cannot be written

context.mode_world_writeable: Specifies that the sharedpreferences data can be read and written by other applications


Third, since Sharedpreference is an interface, it does not provide the ability to write data and read data in this interface. But inside there is an internal editor interface, editor This interface has a series of methods to operate the sharedpreference.

Common Methods of editor interface

Public abstract Sharedpreferences.editor Clear () Empty all the data in the sharedpreferences.
Public abstract Boolean commit () When editor is finished, call this method to commit the modification, and you must call this data to modify
Public abstract Sharedpreferences.editor putxxx (String key, Boolean XXX) The data corresponding to the specified key is deposited to the sharedpreferences, where xxx can be a Boolean, float, int, long, string, and other basic types of values
Public abstract Sharedpreferences.editor Remove (String key) Delete the data item corresponding to the specified key in the Sharedpreferences

Four, below we through the service of a music playback example, "Play" and "pause" two buttons paused after the playback progress to sharedpreferences inside, and then play again, read the progress value for music playback.

Here is the Res/layout/activity_main.xml layout file:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical"    android:background= "@drawable/c1"    tools:context= " Com.example.text.mainactivity$placeholderfragment ">   <button         android:id=" @+id/button01 "        Android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "Play"        Android:textsize= "20SP"        android:layout_margintop= "5DP"/>    <button         android:id= "@+id/ Button02 "        android:layout_width=" match_parent "        android:layout_height=" wrap_content "        android:text = "Pause"        android:textsize= "20sp"        android:layout_margintop= "5DP"/></linearlayout>

Here is a new Musicservice.java interface file:

< strong>

public class Musicservice extends Service{private MediaPlayer player;public ibinder onbind (Intent Intent) {return null;} @Overridepublic void OnCreate () {player=mediaplayer.create (this, r.raw.apple);p layer.setlooping (FALSE);//setting does not automatically loop}/ /The service is destroyed when calling the method @overridepublic void OnDestroy () {Sharedpreferences sp = this.getsharedpreferences ("Music_progress", mode_private);//Get the Editor object, write an integer into the sharepreferences, and remember to commit with commit (), otherwise the write operation Sp.edit () will not be implemented. Putint ("Progress",          Player.getcurrentposition ()). commit ();  The Player.getcurrentposition () method gets the data of the playback progress//Commit () method is to save sharedpreferences obtained data player.stop (); }public void OnStart (Intent Intent, int startid) {//Get Sharedpreferences object Sharedpreferences SP =   This.getsharedpreferences ("Music_progress", mode_private);          Music_progress is the filename of the XML file//player jumps to the last playback progress Player.seekto (Sp.getint ("Progress", 0)); Progress for the value of key,progress in the key-value pair is obtained by player.getcurrentposition (), see the following details//each time the OnStart method is called, the player's progress is set          MediaPlayer the Seekto method, reads the progress, then plays, getint the first parameter is the key name to read, the second parameter is the default initial value.  That is, the initial schedule defaults to 0 player.start (); }}

Note Registering in the Androidmanifest.xml file


Here is the Mainactivity.java main interface file:

public class Mainactivity extends Activity implements onclicklistener{private button B1;private button b2;private Intent i ntent; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); b1= (Button) Findviewbyid (R.id.button01); b2= (button) Findviewbyid ( R.ID.BUTTON02); B1.setonclicklistener (this); B2.setonclicklistener (this); intent = new Intent (Mainactivity.this, Musicservice.class); } @Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.button01:startservice (intent);    Break;case R.id.button02:stopservice (intent);    Break;}}}

here is the result of the operation:



Ben said here, thank you all!



35th: 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.