Android development tutorial on using Sharedpreferences to store data

Source: Internet
Author: User
Tags commit gettext xml parser

sharedpreferences Introduction

Sharedpreferences is a lightweight storage class on the Android platform that holds some common configurations for applications, such as activity status, when activity pauses, Saves the state of this activity to sharedpereferences, when the activity overload, the system callback method Onsaveinstancestate, and then remove the value from Sharedpreferences.
Sharedpreferences provides a storage interface for the Java routine type of data such as long, Int, and string.
Sharedpreferences is similar to the INI configuration file on a Windows system in the past, but it is divided into multiple permissions and can be shared globally.
Hints are ultimately stored in XML, overall efficiency is not particularly high, for conventional lightweight is much better than SQLite, if the real storage is not enough to consider their own definition of file format. XML processing is Dalvik through the native XML parser, such as the Xmlpull method, which is good for memory resource occupancy.

operation mode

Four modes of operation for sharedpreferences data

Context.mode_private
Context.mode_append
Context.mode_world_readable
Context.mode_world_writeable

Context.mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which case the written content overwrites the contents of the original file.
Context.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.
Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications 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 is the most understandable data storage technology in Android, and in fact sharedpreferences is dealing with a key-value (key-value pair) sharedpreferences commonly used to store lightweight data. This is similar to the way in which the map in C + + is stored, which is actually stored in the map format in the last generated. xml file.

Two ways to get sharedpreferences:

1, invoke the Getsharedpreferences () method of the context object

2, call the Activity Object Getpreferences () method

The difference between two ways:

The Sharedpreferences object obtained by invoking the Getsharedpreferences () method of the context object can be shared by other components under the same application.

The Sharedpreferences object obtained by invoking the Getpreferences () method of the activity object can only be used in that activity.

Among them, the Getsharedpreferences () method prototype is:

Getsharedpreferences (String name, int mode);
Name: Generate names of XML files
Mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which case the written content overwrites the contents of the original file.
Mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.
Mode_world_readable: Indicates that the current file can be read by another application and is not recommended
Mode_world_writeable: Indicates that the current file can be written to another application and is not recommended for use

The way to store data using Sharedpreferences is as follows:

Instantiate the Sharedpreferences object (first step)
Sharedpreferences sp = getsharedpreferences ("Test", mode_private);
Instantiating the Sharedpreferences.editor object (step Two)
Sharedpreferences.editor Editor = Mysharedpreferences.edit ();
Saving data in a putstring way
Editor.putstring ("UserName", Etname.gettext (). toString ());
Editor.putstring ("Password", Etpassword.gettext (). toString ());
Submit Current Data
Editor.apply ();
Editor.commit ();
To write data successfully using the Toast Message prompt box
Toast.maketext (Mainactivity.this, "registered successfully", Toast.length_long). Show ();

The way to read data using Sharedpreferences is as follows:

Sharedpreferences sp = getsharedpreferences (Strloginfo, mode_append);
String name = sp.getstring ("UserName", "");
String passwd = sp.getstring ("Password", "");
if (Etname.gettext (). ToString (). Equals (name) && Etpassword.gettext (). ToString (). Equals (passwd)) {
Toast.maketext (Mainactivity.this, "landing success", Toast.length_long). Show ();
} else{
Toast.maketext (mainactivity.this, Login failed, Toast.length_long). Show ();
}

After using Sharedpreferences, the program generates an XML file in "/data/data/Package name/shared_prefs/xxx.xml". The file name depends on the first parameter name of the getsharedpreferences.

<?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?>
<map>
<string name= "UserName" >Name</string>
<string name= "Password" >Password</string>
</map>

The complete code is as follows:

Import android.content.SharedPreferences;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;

public class Mainactivity extends Appcompatactivity {

Private EditText Etname;
Private EditText Etpassword;
Private Button Btnlogin;
Private Button Btnlogup;
Private String Strloginfo = "Test";

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

Etname = (edittext) Findviewbyid (r.id.etname);
Etpassword = (edittext) Findviewbyid (R.id.etpassword);
Btnlogin = (Button) Findviewbyid (R.id.btnlogin);
Btnlogup = (Button) Findviewbyid (R.id.btnlogup);

Btnlogup.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (view view) {
Sharedpreferences sp = getsharedpreferences (Strloginfo, mode_append);
Sharedpreferences.editor Editor = Sp.edit ();

Editor.putstring ("UserName", Etname.gettext (). toString ());
Editor.putstring ("Password", Etpassword.gettext (). toString ());
Editor.commit ();
Toast.maketext (Mainactivity.this, "registered successfully", Toast.length_long). Show ();
}
});
Btnlogin.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (view view) {
Sharedpreferences sp = getsharedpreferences (Strloginfo, mode_append);
String name = sp.getstring ("UserName", "");
String passwd = sp.getstring ("Password", "");
if (Etname.gettext (). ToString (). Equals (name) && Etpassword.gettext (). ToString (). Equals (passwd)) {
Toast.maketext (Mainactivity.this, "landing success", Toast.length_long). Show ();
} else{
Toast.maketext (mainactivity.this, Login failed, Toast.length_long). Show ();
}
}
});

}
}

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.