Sharedpreferences of Android Storage

Source: Internet
Author: User

Sharedpreferences is a mechanism that Android provides to store some simple configuration information, such as some default welcome words, login usernames and passwords, and so on. It is stored as a key-value pair, so that we can easily read and deposit, see below a demonstration example.

Example: Sharedpreferencesdemo
Code logic:
When the app starts, it attempts to read the saved user name and user password from sharedpreferences and displays the results in the appropriate edit box in the UI interface.
Click the login button, if the user name and user password edit box is not empty, save the user name and password entered in the edit box to sharedpreferences, otherwise prompt for a user name or password.
Click the Cancel button to clear the Sharedpreferences, and the edit box is also set to empty.

Operating effect:
Two edit boxes are empty in the initial state


First start enter user name and password and click the login button

Exit the app and restart the app to see the user name and password you entered earlier


Code Listing:
Layout file: Activity_main.xml
<?xml version= "1.0" encoding= "Utf-8"? ><tablelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" Fill_parent "android:stretchcolumns=" 1 "    ; <TableRow> <textview android:gravity= "right" android:textstyle= "bold" and             roid:padding= "3dip" android:text= "User name:"/> <edittext android:id= "@+id/username"    Android:inputtype= "text" android:padding= "3dip" android:scrollhorizontally= "true"/> </TableRow> <TableRow> <textview android:gravity= "right" android:textsty Le= "Bold" android:padding= "3dip" android:text= "User password:"/> <edittext an Droid:id= "@+id/password" android:inputtype= "Textpassword" android:padding= "3dip"/> </table Row> <tablerow Android: gravity= "Right" > <button android:id= "@+id/cancel" android:text= "Cancel"/> <button android:id= "@+id/login" android:text= "Login"/> </tablerow></table Layout>

Java source code file: Mainactivity.java
Package Com.rainsong.sharedpreferencesdemo;import Android.os.bundle;import Android.app.activity;import Android.content.context;import Android.content.sharedpreferences;import Android.content.SharedPreferences.Editor ; Import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.toast;public class MainActivity extends    Activity {private static final String Preferences_name = "Sharedpreferencesdemo";    private static final String Key_username = "USERNAME";    private static final String Key_password = "PASSWORD";    Button Btn_login;    Button Btn_cancel;    EditText Et_username;    EditText Et_password;    Onclicklistener Listener_login;    Onclicklistener Listener_cancel;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Et_username = (EditText) findviEwbyid (R.id.username);        Et_password = (EditText) Findviewbyid (R.id.password);                Listener_login = new Onclicklistener () {public void OnClick (View v) {String username;                String password;                Username = Et_username.gettext (). toString ();                            if (Username.length () < 1) {Toast.maketext (mainactivity.this, "Enter user name",                    Toast.length_long). Show ();                Return                } password = Et_password.gettext (). toString (); if (Password.length () < 1) {Toast.maketext (mainactivity.this, "Please enter password", T Oast.                    Length_long). Show ();                Return                } sharedpreferences pref = Getsharedpreferences (Preferences_name, context.mode_append);                Editor edit = Pref.edit ();                Edit.putstring (Key_username, USERNAME); Edit.putstring (Key_password, PASSWORD);                Edit.commit ();             Toast.maketext (mainactivity.this, "User name:" + username + ", user password:" + Password,toast.length_short). Show ();                }        };        Btn_login = (Button) Findviewbyid (R.id.login);                Btn_login.setonclicklistener (Listener_login);  Listener_cancel = new Onclicklistener () {public void OnClick (View v) {sharedpreferences pref =                Getsharedpreferences (Preferences_name, context.mode_append);                Editor edit = Pref.edit ();                Edit.clear ();                Edit.commit ();                Et_username.settext ("");            Et_password.settext ("");                }        };        Btn_cancel = (Button) Findviewbyid (r.id.cancel);        Btn_cancel.setonclicklistener (Listener_cancel);        Sharedpreferences pref = getsharedpreferences (Preferences_name, context.mode_append);        String username;        String password; USername = pref.getstring (Key_username, "");        Password = pref.getstring (Key_password, "");        Et_username.settext (username);    Et_password.settext (password); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; }}

As you can see from the code above, after using Findviewbyid in OnCreate to get two edittext, use the Getsharedpreferences () method to get the Sharedpreferences object, then use the GetString The () method obtains the value that is saved in it, and finally uses the SetText () method to set its value to a value of two edittext.

When you click the Sign In button, you first get the Sharedpreferences object using the Getsharedpreferences () method, and then call the edit () method to make it editable and use the putstring () Method saves the values in two edittext, and finally commits by using the commit () method.



API Knowledge Points
Public abstract class
Context
Extends Object

Abstract Sharedpreferences getsharedpreferences(String name, int mode)
Retrieve and hold the contents of the Preferences file ' name ', returning a sharedpreferences through which you can Retriev E and modify its values.

public interface
sharedpreferences

Class Overview
Interface for accessing and modifying preference data returned by getsharedpreferences (String, int). For any particular set of preferences, there are a single instance of this class, and all clients share. Modifications to the preferences must go through a Sharedpreferences.editor object to ensure the preference values remain In a consistent state and control when they is committed to storage. Objects that is returned from the various get methods must is treated as immutable by the application.

Abstract Sharedpreferences.editor Edit()
Create a new Editor for these preferences, through which your can make modifications to the data in the preferences and ATO Mically commit those changes back to the Sharedpreferences object.

Abstract String getString(string key, String defvalue)
Retrieve a String value from the preferences.

public static interface
Sharedpreferences.editor

Class Overview
Interface used for modifying values in a Sharedpreferences object. All changes your make in an editor is batched, and not copied back to the original sharedpreferences until your call commit () or Apply ()

Abstract Sharedpreferences.editor Clear()
Mark in the editor to remove all values from the preferences.

Abstract Boolean Commit()
Commit your preferences changes back from this Editor to the Sharedpreferences object it is editing.

Abstract Sharedpreferences.editor putstring(string key, String value)

Set a String value in the preferences editor, to is written back once commit () or apply () is called.


Sharedpreferences of Android Storage

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.