Android learns data storage class sharedpreferences with "Remember Password" feature _android

Source: Internet
Author: User
Tags gettext

Sharedpreferences is a tool class for storing simple data in Android. Imagine that it is a small cookie that stores simple data types (boolean, int, float, long, and string) in the application's private directory by using key-value pairs (data/data/package name/shared_prefs/) In the XML file that you define.

First, Introduction

It provides a lightweight way to store data by Eidt () method to modify the contents of the content, through the commit () method to submit the modified content.

Second, the important method

Public abstract Boolean contains (String key): Checks to see if the file already exists, where key is the file name of the XML.

Edit (): Creates an editor editor for preferences that can modify the data in preferences by creating editor, but must execute the commit () method.

GETALL (): Returns more data in preferences.

Getboolean (String key, Boolean defvalue): Getting boolean data

GetFloat (String key, float defvalue): Get float data

GetInt (String key, int defvalue): getting int type data

Getlong (String key, Long defvalue): Get Long data

GetString (string key, String defvalue): Getting string data

Registeronsharedpreferencechangelistener (Sharedpreferences.onsharedpreferencechangelistener Listener) : Registers a callback function that is invoked when preference changes.

Unregisteronsharedpreferencechangelistener (Sharedpreferences.onsharedpreferencechangelistener Listener) : Deletes the current callback function.

Third, the important interface Sharedpreferences.editor

1. Introduction

Used to modify the contents of the Sharedpreferences object, all changes are made in the editor batch, not copied back to the original sharedpreferences or persistent storage until you invoke commit () to persist the storage.

2. Important Methods

Clear (): Clears the content.

Commit (): Commit modification

Remove (String key): Delete preference

The following is the "Remember Password" feature

Iv. examples

The effect chart is as follows

Home

The page after successful login

When the first time you click on "Remember Password", the second time when you open the page

2. Code

Layout file Login.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:gravity=" right "Android: Layout_gravity= "Right" android:background= "@drawable/default_bg" android:orientation= "vertical" > < Tablelayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:stretchColumns= "1" > <tablerow android:gravity= "center" android:layout_gravity= "Center" > <imageview android:layout_width= " Fill_parent "android:layout_height=" wrap_content "android:id=" @+id/ivlogo "> </ImageView> </tablerow > </TableLayout> <tablelayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:stretchcolumns= "1" > <tablerow android:layout_margintop= "100dip" > <textview android:layout_ Width= "Wrap_content" android:layout_marginleft= "20dip" android:gravity= "Center_vertical" android:layout_height= "Wrap_content" android:id= "@+id/tvaccount" android:text= "account Number:" Android:textsize= "20SP" > < /textview> <edittext android:layout_width= "70px" android:layout_height= "wrap_content" android:id= "@+id/" Etaccount "android:layout_marginright=" 20dip "android:maxlength=" ></EditText> </TableRow> < TableRow android:layout_margintop= "10dip" > <textview android:layout_width= "wrap_content" Android:layout_
 height= "Wrap_content" android:id= "@+id/tvpw" android:layout_marginleft= "20dip" android:gravity= "center_vertical" android:text= "Password:" android:textsize= "20SP" > </TextView> <edittext android:layout_width= "70px" Android: layout_height= "Wrap_content" android:layout_marginright= "20dip" android:id= "@+id/etpw" android:inputtype= " Textpassword "></EditText> </TableRow> </TableLayout> <linearlayout xmlns:android=" http:// Schemas.android.com/apk/res/android "android:layout_width=" Wrap_content "Android:layout_height= "wrap_content" android:orientation= "horizontal" android:layout_margintop= "5dip" android:layout_marginright= "20dip" > <textview android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:id= "@+id" /tvclear "android:text=" android:textcolor= "#aa0000" android:textsize= "12px" ></TextView> </ linearlayout> <tablelayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android: layout_margintop= "20dip" > <tablerow android:gravity= "center" android:layout_width= "Fill_parent" > < Button android:layout_width= "100px" android:layout_height= "wrap_content" android:id= "@+id/btnlogin" android:layout _gravity= "center" android:text= "login" ></Button> <button android:layout_width= "100px" Android:layout_ height= "Wrap_content" android:id= "@+id/btnexit" android:layout_gravity= "center" android:text= "Exit" ></Button > </TableRow> </TableLayout> <linearlayout xmlns:android= "HTTp://schemas.android.com/apk/res/android "android:layout_width=" wrap_content "android:layout_height=" Wrap_ Content "android:orientation=" horizontal "android:layout_margintop=" 25dip "> <checkbox android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:id=" @+id/cbrp "android:text=" Remember Password "android:textSize=" 12px "></CheckBox> <checkbox android:layout_width=" wrap_content "android:layout_height=" Wrap_content " Android:id= "@+id/cbal" android:text= "Automatic Login" android:textsize= "12px" ></CheckBox> </LinearLayout> <

 /linearlayout>

Java code

Package COM.WJQ;
Import android.app.Activity;
Import Android.content.Context;
Import android.content.SharedPreferences;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.Display;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.CheckBox;
Import Android.widget.CompoundButton;
Import Android.widget.EditText;
Import Android.widget.TextView;

Import Android.widget.Toast;
Import Com.wjq.beans.User;

Import Com.wjq.func.UserMgr;
 public class Login extends activity {private EditText etaccount;
 Private EditText ETPW;
 Private Button Btnlogin;
 Private Button Btnexit;
 Private CheckBox CBRP;
 Private CheckBox Cbal;
 Private Usermgr usermgr;
 private user user;
 Private Sharedpreferences sp;

 Private TextView tvclear; * * * (non-javadoc) * * @see android.app.activity#oncreate (android.os.Bundle)/@Override protected void OnCreate (B Undle savedinstancestate) {//TODO auto-generated Method StUB Super.oncreate (savedinstancestate);

 Setcontentview (R.layout.login);
 Etaccount = (edittext) Findviewbyid (R.id.etaccount);
 ETPW = (edittext) Findviewbyid (R.ID.ETPW);
 CBRP = (CheckBox) Findviewbyid (R.ID.CBRP);
 Cbal = (CheckBox) Findviewbyid (R.id.cbal);
 Btnlogin = (Button) Findviewbyid (R.id.btnlogin);
 Btnexit = (Button) Findviewbyid (r.id.btnexit);

 Tvclear= (TextView) Findviewbyid (r.id.tvclear);
 Initconfig (); CBRP. Setoncheckedchangelistener (New Compoundbutton.oncheckedchangelistener () {@Override public void Oncheckedchang
  Ed (Compoundbutton Buttonview, Boolean ischecked) {sp = getsharedpreferences ("UserInfo", 0);
  Sp.edit (). Putboolean ("CBRP", ischecked). commit ();

 }

 }); Cbal. Setoncheckedchangelistener (New Compoundbutton.oncheckedchangelistener () {@Override public void Oncheckedchang
  Ed (Compoundbutton Buttonview, Boolean ischecked) {sp = getsharedpreferences ("UserInfo", 0);
  Sp.edit (). Putboolean ("Cbal", ischecked). commit ();
 }

 }); Btnlogin.setOnclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {user = new user (Etaccount.gettext (). To

 String (), Etpw.gettext (). toString ());
 LOG.I ("tag", "Account:" + etaccount.gettext (). toString ());

 LOG.I ("tag", "Password:" + etpw.gettext (). toString ());
 Usermgr = new Usermgr ();

 Boolean flag = usermgr.checkuser (user, login.this); if (!flag) {Toast.maketext (login.this, "User authentication Error!")
 ", 1000). Show (); else {if (cbrp.ischecked ()) {sp = getsharedpreferences ("UserInfo", Context.mode_world_writeable |
  
  context.mode_world_readable);
  Sp.edit (). Putstring ("Account", Etaccount.gettext (). toString ()). commit ();
  Sp.edit (). putstring ("Password", Etpw.gettext (). toString ()). commit ();

 }
 }
 }

 });
 Btnexit.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {system.exit (0);
 
 }
 }); Tvclear.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {sp=getsharedpreferences ("
 
UserInfo ", 0); Sp.edit (). Clear (). commit ();
 }});
 }//Initialize configuration private void Initconfig () {sp = getsharedpreferences ("UserInfo", 0);
 Etaccount.settext (sp.getstring ("account", null));
 Etpw.settext (sp.getstring ("password", null));
 Cbal.setchecked (Sp.getboolean ("Cbal", false));
 Cbrp.setchecked (Sp.getboolean ("CBRP", false));

 }
}

Description

1. Write content

 SP = getsharedpreferences ("UserInfo", 0);
  Sp.edit (). Putboolean ("Cbal", ischecked). commit ();
  UserInfo refers to the file name of the XML file, and if the file already exists, the value of the content "IsChecked" is written directly to it, the editor is first created through the Sharedpreferences edit () method, and then the commit () method is invoked to modify

2. Read the content

SP = getsharedpreferences ("UserInfo", 0);
 Etaccount.settext (sp.getstring ("account", null));
 Etpw.settext (sp.getstring ("password", null));
 Cbal.setchecked (Sp.getboolean ("Cbal", false));
 Cbrp.setchecked (Sp.getboolean ("CBRP", false));

The above is the entire content of this article, I hope to help you learn.

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.