• android 保存 用户名和密码 设置等应用信息优化


    此文为转载:为尊重原创作者添加原始链接:

    http://www.cnblogs.com/likwo/p/3875909.html

    1、传统的保存用户名,密码方式 SharedPreferences

      

    1
    2
    Editor editor = shareReference.edit();
    editor.putString(KEY_NAME,"username_value");

      

    通过这样的方法,能够基本满足需求,比如有用户名,那么就Editor.putString存放就好。

    但是这样的方法有一些弊端:

    (1)在存放一些集合信息,存储ArrayList就不合适

    (2)如果针对用户,新增加了很多熟悉,比如性别,头像等信息,那么需要一个一个的添加put和get方法,非常的繁琐。

    2、通过序列化对象,将对象序列化成base64编码的文本,然后再通过SharedPreferences 保存,那么就方便很多,只需要在对象里增加get和set方法就好。

    3、 序列换通用方法, 将list对象或者普通的对象序列化成字符串

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    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{
            //实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //然后将得到的字符数据装载到ObjectOutputStream
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            //writeObject 方法负责写入特定类的对象的状态,以便相应的readObject可以还原它
            oos.writeObject(list);
            //最后,用Base64.encode将字节文件转换成Base64编码,并以String形式保存
            String listString = new String(Base64.encode(baos.toByteArray(),Base64.DEFAULT));
            //关闭oos
            oos.close();
            return listString;
            }
         
        public static  String obj2Str(Object obj)throws IOException
        {
            if(obj == null) {
                return "";
            }
                  //实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    //然后将得到的字符数据装载到ObjectOutputStream
                    ObjectOutputStream oos = new ObjectOutputStream(baos);
                    //writeObject 方法负责写入特定类的对象的状态,以便相应的readObject可以还原它
                    oos.writeObject(obj);
                    //最后,用Base64.encode将字节文件转换成Base64编码,并以String形式保存
                    String listString = new String(Base64.encode(baos.toByteArray(),Base64.DEFAULT));
                    //关闭oos
                    oos.close();
                    return listString;
        }
         
        //将序列化的数据还原成Object
        public 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 block
                e.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 block
                e.printStackTrace();
            }
            return stringList;
            }
     
    }

    4、 要保存的用户对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    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;
        // 原始密码
         
        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、编写SharedPreUtil ,实现对对象的读取和保存

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    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
    {
         
        // 用户名key
        public final static String KEY_NAME = "KEY_NAME";
     
        public final static String KEY_LEVEL = "KEY_LEVEL";
         
         
        private static SharedPreUtil s_SharedPreUtil;
         
        private static UserEntity s_User = null;
     
        private SharedPreferences msp;
         
        // 初始化,一般在应用启动之后就要初始化
        public static synchronized void initSharedPreference(Context context)
        {
            if (s_SharedPreUtil == null)
            {
                s_SharedPreUtil = new SharedPreUtil(context);
            }
        }
         
        /**
         * 获取唯一的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 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();
         
                 
                //获取序列化的数据
                String str = msp.getString(SharedPreUtil.KEY_NAME, "");
                 
                try {
                    Object obj = SerializableUtil.str2Obj(str);
                    if(obj != null){
                        s_User = (UserEntity)obj;
                    }
                     
                } catch (StreamCorruptedException 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、 调用Activity代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    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;
         
        @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);
             
            button = (Button)findViewById(R.id.btn);
             
             
         //保存到本地
            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);
                      
                     //用户名,密码保存在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());
            }
             
        }
         
        @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;
        }
         
    }

      

      对应的布局文件

     来个截图

     

    7、 如果我们的应用程序有不太复杂的保存需求,那么就可借助 SerializableUtil list2String 将list对象保存为文本,然后在通过文本的方式来读取,这样就不用使用数据库了,会轻量很多。

  • 相关阅读:
    P2761 软件补丁问题
    CF1335F Robots on a Grid
    [bzoj2088]P3505 [POI2010]TEL-Teleportation
    CF1335E Three Blocks Palindrome
    P3831 [SHOI2012]回家的路
    P4568 [JLOI2011]飞行路线(分层图)
    P4774 [NOI2018]屠龙勇士
    P2480 [SDOI2010]古代猪文
    CF #632 (Div. 2) 对应题号CF1333
    BSGS 和扩展
  • 原文地址:https://www.cnblogs.com/liyuzhao/p/4013121.html
Copyright © 2020-2023  润新知