android - Use sharedPreference to save account and password -
public class loginactivity extends baseactivity{ private sharedpreferences pref; private sharedpreferences.editor editor; private edittext accountedit; private edittext passwordedit; private button login; private checkbox rememberpass; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.login); accountedit =(edittext)findviewbyid(r.id.account); passwordedit = (edittext)findviewbyid(r.id.password); rememberpass=(checkbox)findviewbyid(r.id.remember_pass); login = (button)findviewbyid(r.id.login); editor.putboolean("remember_password",false); boolean isremember = pref.getboolean("remember_password",false); if(isremember){ string account = pref.getstring("account", ""); string password =pref.getstring("password", ""); accountedit.settext(account); passwordedit.settext(password); rememberpass.setchecked(true); } login.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { string account =accountedit.gettext().tostring(); string password = passwordedit.gettext().tostring(); if (account.equals("admin")&& password.equals("123456")) { editor = pref.edit(); if(rememberpass.ischecked()) { editor.putboolean("remember_password",true); editor.putstring("account",account); editor.putstring("password",password); } else { editor.clear(); } editor.commit(); intent intent = new intent(loginactivity.this,mainactivity.class); startactivity(intent); finish(); } else { toast.maketext(loginactivity.this,"account password invalid", toast.length_long).show(); } } }); } }
i use eclipse code android.i got error in logcat,which nullpointerexception cause "boolean isremember = pref.getboolean("remember_password",false);" don't know why.how use getboolean correctly? in advance.
because pref=null
at
boolean isremember = pref.getboolean("remember_password",false);
initialized
before used
sharedpreferences pref= preferencemanager.getdefaultsharedpreferences(loginactivity.this);
Comments
Post a Comment