Android saves user name and password settings and other application information Optimization

Source: Internet
Author: User

Android saves user name and password settings and other application information Optimization
1. The traditional user name and password mode are SharedPreferences 12 Editor editor = shareReference. edit (); editor. putString (KEY_NAME, "username_value"); by using this method, you can basically meet your needs. For example, if you have a user name, then Editor. you can store putString. However, this method has some drawbacks: (1) it is inappropriate to store some set information and store ArrayList (2) it is new to users, such as gender, adding put and get Methods One by one is very cumbersome. 2. serialize an object to a base64 encoded text, and save the object through SharedPreferences. This is much more convenient, just add the get and set methods to the object. 3. For general methods of serialization, serialize the list object or common object to a string of 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 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. streamCo RruptedException; import java. util. list; import android. util. base64; public class SerializableUtil {public static <E> String list2String (List <E> list) throws IOException {// instantiate a ByteArrayOutputStream object, used to load the compressed ByteArrayOutputStream baos = new ByteArrayOutputStream (); // then load the obtained character data to ObjectOutputStream oos = new ObjectOutputStream (baos ); // The writeObject method is used to write the state of the object of a specific class, so that the corresponding rea DObject can restore its oos. writeObject (list); // Finally, use Base64.encode to convert the byte file to Base64 encoding, and save String listString = new String (Base64.encode (baos. toByteArray (), Base64.DEFAULT); // disable oos. close (); return listString;} public static String obj2Str (Object obj) throws IOException {if (obj = null) {return "" ;}// instantiate a ByteArrayOutputStream Object, used to load the compressed ByteArrayOutputStream baos = new ByteArrayOutputStream (); // Then load the obtained character data to ObjectOutputStream oos = new ObjectOutputStream (baos); // The writeObject method is responsible for writing the status of the object of a specific class, so that the corresponding readObject can restore its oos. writeObject (obj); // Finally, use Base64.encode to convert the byte file to Base64 encoding, and save String listString = new String (Base64.encode (baos. toByteArray (), Base64.DEFAULT); // disable oos. close (); return listString;} // restore serialized data to Object public static Object str2Obj (String str) th Rows streamcompuptedexception, 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 block e. printStackTrace ();} return null;} public static <E> List <E> string2List (Str Ing 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 block e. printStackTrace ();} re Turn stringList;} 4. User object to be saved: 12345678910111213141516171819202122232425262728293031323334353637 package com. example. imagedemo; import java. io. serializable; import android. annotation. suppressLint; public class UserEntity implements Serializable {private static final long serialVersionUID =-5683261099918171030l; private String userName; // original password public String getUserName () {return userName;} pu Blic 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 read and save the object by 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081. 828384858687888990919293949596979899100101102103104105106107108109110111112113 package com. example. imagedemo; import java. io. IOException; import java. io. streamcomputedexception; import android. content. context; import android. content. intent; import android. content. sharedPreferences; import android. content. sharedPreferences. editor; public class SharedPreUtil {// user name key public final static String KEY_NAM E = "KEY_NAME"; public final static String KEY_LEVEL = "KEY_LEVEL"; private static SharedPreUtil s_SharedPreUtil; private static UserEntity s_User = null; private SharedPreferences msp; // initialization, generally, public static synchronized void initSharedPreference (Context context) {if (s_SharedPreUtil = null) {s_SharedPreUtil = new SharedPreUtil (context);} must be initialized after the application is started );}} /*** get a unique instance *** @ return */publ Ic 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. o Bj2Str (user);} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} editor. putString (KEY_NAME, str); editor. commit (); s_User = user;} public synchronized UserEntity getUser () {if (s_User = null) {s_User = new UserEntity (); // obtain the serialized data String str = msp. getString (SharedPreUtil. KEY_NAME, ""); try {Object obj = SerializableUtil. str2Obj (str); if (obj! = Null) {s_User = (UserEntity) obj ;}} catch (streamjavasuptedexception e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. 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 123456789101112 1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 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. ed ItText; public class ActivityMain extends Activity {EditText edit_pwd; EditText edit_name; Button button; @ Override protected 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); bu Tton = (Button) findViewById (R. id. btn); // save it to the local button. setOnClickListener (new OnClickListener () {@ Override public 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. The password is stored in SharedPreferences SharedPreUtil. getInstance (). putUser (user) ;}}); Button delBt N = (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 () ;}@ Override public 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 ;}} corresponding layout file 1234567891011121314151617181920212223242526272829303132333435363738 <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: paddingBottom = "@ dimen/activity_vertical_margin" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/activity_vertical_margin" android: orientation = "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_content" android: layout_height = "40dip" android: text = "clear"> </Button> </LinearLayout>

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.