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

来源:互联网 发布:校友会网站 源码 编辑:程序博客网 时间:2024/05/16 10:00

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;
 
publicclass SerializableUtil {
     
    publicstatic <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();
        returnlistString;
        }
     
    publicstatic  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();
                returnlistString;
    }
     
    //将序列化的数据还原成Object
    publicstatic 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{
            returnois.readObject();
        }catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        returnnull;
     
    }
     
    publicstatic <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();
        }
        returnstringList;
        }
 
}

 

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
{
     privatestatic final long serialVersionUID = -5683263669918171030L; 
 
    privateString userName;
    // 原始密码
     
    publicString getUserName()
    {
        returnuserName;
    }
 
    publicvoid setUserName(String userName)
    {
        this.userName = userName;
    }
 
    publicString getPassword()
    {
        returnpassword;
    }
 
    publicvoid setPassword(String password)
    {
        this.password = password;
    }
 
    privateString 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;
 
publicclass SharedPreUtil
{
     
    // 用户名key
    publicfinal staticString KEY_NAME = "KEY_NAME";
 
    publicfinal staticString KEY_LEVEL = "KEY_LEVEL";
     
     
    privatestatic SharedPreUtil s_SharedPreUtil;
     
    privatestatic UserEntity s_User =null;
 
    privateSharedPreferences msp;
     
    // 初始化,一般在应用启动之后就要初始化
    publicstatic synchronizedvoid initSharedPreference(Context context)
    {
        if(s_SharedPreUtil == null)
        {
            s_SharedPreUtil =new SharedPreUtil(context);
        }
    }
     
    /**
     * 获取唯一的instance
     *
     * @return
     */
    publicstatic synchronized SharedPreUtil getInstance()
    {
        returns_SharedPreUtil;
    }
     
    publicSharedPreUtil(Context context)
    {
        msp = context.getSharedPreferences("SharedPreUtil",
                Context.MODE_PRIVATE | Context.MODE_APPEND);
    }
     
    publicSharedPreferences getSharedPref()
    {
        returnmsp;
    }
 
     
    publicsynchronized voidputUser(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;
    }
     
    publicsynchronized 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();
            }
        }
         
        returns_User;
    }
     
    publicsynchronized voidDeleteUser()
    {
        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;
 
publicclass ActivityMain extends Activity
{
     
    EditText edit_pwd;
    EditText edit_name;
    Button button;
     
    @Override
    protectedvoid 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(newOnClickListener()
        {
             
            @Override
            publicvoid 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(newOnClickListener()
            {
                 
                @Override
                publicvoid 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
    publicboolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        returntrue;
    }
     
}

  

  对应的布局文件

 来个截图

 

 

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


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


0 0