Learn android & lt; Data Storage (1) SharedPreferences attribute file from scratch. 35. & gt ;,

Source: Internet
Author: User

Learn android from scratch <data storage (1) SharedPreferences attribute file. 35 ..>,

There are five ways to save data in android:

Shared Preferences
Store private primitive data in key-value pairs.
Key-value pairs of the corresponding attribute file storage
Internal Storage
Store private data on the device memory.
Device memory storage
External Storage
Store public data on the shared external storage.
External memory storage, such as memory cards
SQLite Databases
Store structured data in a private database.
Sqlite database storage
Network Connection

Store data on the web with your own network server. network Storage

Today, we will take a look at the Shared Preferences attribute file storage method to store simple data.

We can use Shared Preferences to store simple booleans, floats, ints, longs, and strings data and save it as an xml file as a key-value pair.


To instantiate Shared Preferences, we can use

GetSharedPreferences () andgetPreferences()These two methods

The first method requires passing in a file name and storage mode.

The second method has only one property file by default. You only need to pass in a storage mode.


Storage Mode:

MODE_PRIVATE is only available for this application

MODE_APPEND: appendable

 MODE_WORLD_READABLE, Which can be read by other applications

MODE_WORLD_WRITEABLE. Can be written by other applications


For more information, see code comments.



Xml file

<RelativeLayout 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: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <Button android: id =" @ + id/button1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentTop =" true "android: layout_centerHorizontal = "true" android: layout_marginTop = "89dp" android: text = "storage Information"/> <Button android: id = "@ + id/button2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignRight = "@ + id/button1" android: layout_below = "@ + id/button1" android: layout_marginTop = "36dp" android: text = "read information"/> </RelativeLayout>

JAVA files


Package com. example. sharedpreferences; import android. app. activity; import android. content. sharedPreferences; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {private SharedPreferences sharedPreferences; private Button saveData, getDate; public static final String FILENAME = "flyou"; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); sharedPreferences = getSharedPreferences (FILENAME, MODE_PRIVATE); saveData = (Button) this. findViewById (R. id. button1); getDate = (Button) this. findViewById (R. id. button2); saveData. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubSharedPreferences. editor editor = sharedPreferences. edit (); editor. putString ("username", "jay"); editor. putString ("password", "553274238"); Boolean flag = editor. commit (); Toast. makeText (MainActivity. this, "execution completed, execution result: -->" + flag, 2 ). show () ;}}); getDate. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubString username = sharedPreferences. getString ("username", "no matching information found"); String password = sharedPreferences. getString ("password", "User password not found"); Toast. makeText (MainActivity. this, "username: -->" + username + ", password: -->" + password, 2 ). show ();}});}}




Next, use the change method to implement the function of remembering the account and password locally.

It may involve some unknown knowledge. You can first understand and review other components you have learned.


Xml file

Main Interface

<RelativeLayout 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: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" tools: context = ". mainActivity "> <TextView android: id =" @ + id/textView1 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentLeft =" true "android: layout_alignParentTop = "true" android: layout_marginLeft = "19dp" android: layout_marginTop = "42dp" android: text = "username"/> <TextView android: id = "@ + id/textView2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignRight = "@ + id/textView1" android: layout_below = "@ + id/textView1" android: layout_marginTop = "58dp" android: text = "password"/> <EditText android: id = "@ + id/editText1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignBaseline = "@ + id/textView1" android: layout_alignBottom = "@ + id/textView1" android: layout_marginLeft = "40dp" android: layout_toRightOf = "@ + id/textView1" android: EMS = "10"> <requestFocus/> </EditText> <EditText android: id = "@ + id/editText2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignBaseline = "@ + id/textView2" android: Layout = "@ + id/textView2" android: layout_alignLeft = "@ + id/editText1" android: EMS = "10" android: inputType = "textPassword"/> <CheckBox android: id = "@ + id/checkBox1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignBottom = "@ + id/button1" android: layout_alignRight = "@ + id/editText2" android: text = "Remember password"/> <Button android: id = "@ + id/button2" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignBaseline = "@ + id/button1" android: layout_alignBottom = "@ + id/button1" android: layout_alignParentLeft = "true" android: text = "register account"/> <Button android: id = "@ + id/button1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_centerVertical = "true" android: layout_toLeftOf = "@ + id/checkBox1" android: text = "login"/> </RelativeLayout>

Logon Interface

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/textView3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Medium Text"        android:textAppearance="?android:attr/textAppearanceMedium" /></LinearLayout>

JAVA files

Package com. example. sharepreferencesdemo; import android. app. activity; import android. app. progressDialog; import android. content. intent; import android. content. sharedPreferences; import android. OS. bundle; import android. view. view; import android. widget. button; import android. widget. checkBox; import android. widget. editText; public class MainActivity extends Activity {private SharedPreferences sharedPreference S; private Button login; private CheckBox checkBox; private EditText username, password; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); login = (Button) this. findViewById (R. id. button1); checkBox = (CheckBox) this. findViewById (R. id. checkBox1); username = (EditText) this. findViewById (R. id. editText1); password = (EditTex T) this. findViewById (R. id. editText2); sharedPreferences = getPreferences (MODE_PRIVATE); // instantiate the sharedPreferences object String usernameString = sharedPreferences through getPreferences. getString ("username", ""); // read username. setText (usernameString); // set the content in the edit box // obtain the selected status of the check box. if so, remember the password if (sharedPreferences. getBoolean ("checked", false) {// obtain the password String passwordString = sharedPreferences. getString ("password", ""); // Set the password in the edit box. setText (passwordString);} login. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub // instantiate the Editor object by using the edit method to store information about SharedPreferences. editor editor = sharedPreferences. edit (); // store information in the form of key-value pairs editor. putString ("username", username. getText (). toString (); editor. putString ("password", password. getText (). toString (); // judge If (checkBox. isChecked () {editor. putBoolean ("checked", true);} else {editor. putBoolean ("checked", false);} // executes the storage operation editor. commit (); // set the progress dialog box final ProgressDialog dialog = new ProgressDialog (MainActivity. this); // set the title dialog. setTitle ("User Logon"); // sets the prompt message dialog. setMessage ("logging in, please wait ...... "); // Start progress dialog box dialog. onStart (); // delayed Thread Operation new Thread () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {// sleep for 3 seconds Thread. sleep (3*1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {// the dialog box disappears. dismiss (); // sets Intent intent Intent = new Intent (MainActivity. this, main. class); // transfer intent information intent. putExtra ("username", username. getText (). toString (); // start activity to jump to startActivity (intent); MainActivity. this. finish ();}}}. start (); // start the thread operation // display the dialog box dialog. show ();}});}}

Login interface


Package com. example. sharepreferencesdemo; import android. app. activity; import android. content. intent; import android. graphics. color; import android. OS. bundle; import android. view. gravity; import android. widget. textView; public class main extends Activity {private TextView text; @ Overrideprotected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stubsuper. onCreate (savedInstanceState); super. setContentView (R. layout. linearlayout); text = (TextView) this. findViewById (R. id. textView3); Intent intent = getIntent (); text. setTextSize (15); text. setGravity (Gravity. CENTER_HORIZONTAL); text. setTextColor (Color. CYAN); text. setText ("Welcome:" + intent. getStringExtra ("username "));}}





Do not click Remember password, the second login.


Click Remember password to log on


Click Remember password to log on for the third time



This article introduces the storage of SharedPreferences attribute files. We can quickly store and conveniently read small data.


Next prediction: Internal 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.