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;
}
}
對應的布局文件
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
<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/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
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="保存" >
</Button>
<Button
android:id="@+id/btn_del"
android:layout_width="wrap_content"
android:layout_height="40dip"
android:text="清除" >
</Button>
</LinearLayout>