Android Save user name and password settings and other application information optimization

Source: Internet
Author: User

1, the traditional saving user name, password mode sharedpreferences

Editor editor = Sharereference.edit (); Editor.putstring (Key_name, "Username_value");

  

In this way, can basically meet the needs, such as the user name, then editor.putstring storage is good.

But there are some drawbacks to this approach:

(1) storing ArrayList is not appropriate when storing some collection information

(2) If the user, the new add a lot of familiar, such as gender, Avatar and other information, then need a one to add put and get method, very cumbersome.

2, through the serialization of objects, the object is serialized into Base64 encoded text, and then saved by Sharedpreferences, then it is much more convenient, just need to add the get and set method in the object is good.

3, the sequence of the general method, the list object or ordinary objects serialized into a string

Package Com.example.imagedemo;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.io.streamcorruptedexception;import Java.util.list;import Android.util.base64;public class SerializableUtil { public static <E> String list2string (list<e> List) throws ioexception{//instantiates a Bytearrayoutputstream object, Used to load the compressed byte file Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();// The resulting character data is then loaded into objectoutputstreamobjectoutputstream Oos = new ObjectOutputStream (BAOs); The//writeobject method is responsible for writing the state of the object of a particular class, So that the corresponding readobject can restore it oos.writeobject (list);//Finally, convert the byte file to Base64 encoding with Base64.encode and save string As String liststring = new String (Base64.encode (Baos.tobytearray (), Base64.default));//close Oosoos.close (); return liststring;}      public static String obj2str (Object obj) throws ioexception{if (obj = = null) {return "";} Instantiates a Bytearrayoutputstream object that is used to mount the compressed byte file Bytearrayoutputstream BAOs = new ByteaRrayoutputstream ()///Then load the resulting character data to objectoutputstreamobjectoutputstream Oos = new ObjectOutputStream (BAOs);// The WriteObject method is responsible for writing the state of the object of a particular class so that the corresponding readobject can restore it oos.writeobject (obj);//Finally, Convert the byte file to Base64 encoding with Base64.encode and save string As String liststring = new String (Base64.encode (Baos.tobytearray (), Base64.default));//close Oosoos.close (); return liststring;} Restores serialized data to objectpublic static Object str2obj (String str) throws streamcorruptedexception,ioexception{byte[] MByte = Base64.decode (Str.getbytes (), base64.default); Bytearrayinputstream Bais = new Bytearrayinputstream (mbyte); ObjectInputStream ois = new ObjectInputStream (Bais); try { return Ois.readobject ();} catch (ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return null;} public static <E> list<e> string2list (String str) throws streamcorruptedexception,ioexception{byte[] MByte = Base64.decode (Str.getbytes (), base64.default); Bytearrayinputstream Bais = new Bytearrayinputstream (mbyte); ObjectInputStream ois = new ObjectInputStream (Bais);  List<e> stringlist = null;try {stringlist = (list<e>) ois.readobject ();} catch (ClassNotFoundException E) {// TODO auto-generated catch Blocke.printstacktrace ();} return stringlist;}}

4. User objects to save

Package Com.example.imagedemo;import Java.io.serializable;import Android.annotation.suppresslint;public class Userentity implements Serializable {private static final long serialversionuid = -5683263669918171030l;  private string username;//original password public string GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} private String password;}

  

5, write Sharedpreutil, to achieve the object read and save

Package Com.example.imagedemo;import Java.io.ioexception;import Java.io.streamcorruptedexception;import Android.content.context;import Android.content.intent;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;public class sharedpreutil{//user name Keypublic final static String key_name = "KEY    _name ";  Public final static String Key_level = "Key_level";p rivate static sharedpreutil s_sharedpreutil;private static userentity S_user = null;private sharedpreferences msp;//initialization, typically initializes public static synchronized void Initsharedpreference After the application is started ( Context context) {if (S_sharedpreutil = = null) {S_sharedpreutil = new Sharedpreutil (context);}} /** * Get Unique instance * * @return */public static synchronized Sharedpreutil getinstance () {return s_sharedpreutil;} Public Sharedpreutil (Context context) {MSP = Context.getsharedpreferences ("Sharedpreutil", Context.mode_private | Context.mode_append);} Public Sharedpreferences Getsharedpref () {return MSP;} public synchronized void PutusER (userentity user) {Editor editor = Msp.edit (); String str= ""; try {str = serializableutil.obj2str (user);} catch (IOException e) {//TODO auto-generated catch Blocke.print StackTrace ();} Editor.putstring (KEY_NAME,STR); Editor.commit (); s_user = User;} Public synchronized userentity GetUser () {if (S_user = = null) {S_user = new userentity ();//Gets the serialized data string str = Msp.getstrin  G (Sharedpreutil.key_name, ""); try {Object obj = serializableutil.str2obj (str); if (obj! = null) {S_user = (userentity) obj;}} catch (Streamcorruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TOD O auto-generated catch Blocke.printstacktrace ();}} return s_user;} Public synchronized void DeleteUser () {Editor editor = Msp.edit (); Editor.putstring (Key_name, ""); Editor.commit (); s_ User = null;}}

  

6. Call Activity Code

Package Com.example.imagedemo;import Android.app.activity;import Android.os.bundle;import android.text.TextUtils; Import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;public class Activitymain extends Activity{edittext edit_pwd; EditText Edit_name; Button button, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Sharedpreutil.initsharedpreference (Getapplicationcontext ()); edit_pwd = (EditText) Findviewbyid (R.id.pwd); edit_ Name = (EditText) Findviewbyid (r.id.name), Button = (button) Findviewbyid (R.ID.BTN); Save to local Button.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {String name = Edit_name. GetText (). toString ();  String pwd = Edit_pwd.gettext (). toString (); userentity user = new Userentity (); User.setpassword (PWD);  User.setusername (name); User name, password saved in sharedpreferences SHAREDPREUTIL.GEtinstance (). Putuser (user);});    Button delbtn = (button) Findviewbyid (R.id.btn_del); Delbtn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {sharedpreutil.getinstance ().    DeleteUser ();    Edit_name.settext ("");    Edit_pwd.settext ("");});    userentity user = Sharedpreutil.getinstance (). GetUser (); if (! Textutils.isempty (User.getpassword ()) &&!    Textutils.isempty (User.getusername ())) {Edit_name.settext (User.getusername ());    Edit_pwd.settext (User.getpassword ()); }} @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is Present.getmenuinflater (). Inflate (R.menu.activity_main, menu); return true;}}

  

The corresponding layout file

<linearlayout 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:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" Android:o rientation= "Vertical" tools:context= ". Activitymain "> <edittext android:id=" @+id/name "android:hint=" Please input name "Android        : layout_width= "fill_parent" android:layout_height= "40dip"/> <edittext android:id= "@+id/pwd"     Android:layout_width= "fill_parent" android:hint= "Please input password" android:layout_height= "40dip"/> <button android:id= "@+id/btn" android:layout_width= "wrap_content" android:layout_height= "40dip "Android:text= "Save" > </Button> <button android:id= "@+id/btn_del" android:layout_width= "Wrap_cont Ent "android:layout_height=" 40dip "android:text=" clear "> </Button></LinearLayout>

Have a

7, if our application has less complex preservation requirements, then you can use Serializableutil list2string to save the list object as text, and then read through the text, so that the database is not used, it is a lot lighter.

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.