今天写了个Android登录界面的小程序,要求将用户名和密码在点击保存密码的CheckBox的情况下被保存在文件中。再次打开这个app的时候如果存信息的文件里面有东西就回显在对应的userName和passwd的EditText中。
但是在重新开启app的时候没有显示之前保存的信息。
分析:
之前代码:
在SaveUserInfo类里面:
<span style="font-size:18px;">public boolean saveInfo(Context contex, String name, String passwd){
File file = new File(contex.getFilesDir(), fname);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write((name+"$#"+passwd).getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}</span>
在GetUserInfo类里面:
<span style="font-size:18px;">public Map<String, String> getInfo(Context context) {
Map<String, String> map = new HashMap<String, String>();
File file = new File(context.getFilesDir(), fname);
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String[] infos = br.readLine().split("$#");
for(String str : infos){
Log.e(tag, str);
}
map.put("name", infos[0]);
map.put("passwd", infos[1]);
Log.e(tag, "Map got 'put'");
br.close();
fis.close();
return map;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}</span>
改进:
<span style="font-size:18px;">public Map<String, String> getInfo(Context context) {
Map<String, String> map = new HashMap<String, String>();
File file = new File(context.getFilesDir(), fname);
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String[] infos = br.readLine().split("\\$\\#");
for(String str : infos){
Log.e(tag, str);
}
map.put("name", infos[0]);
map.put("passwd", infos[1]);
Log.e(tag, "Map got 'put'");
br.close();
fis.close();
return map;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}</span>
加上转义字符就行了。可能原因,写的时候用的字节流,读的时候用的字符流,拆分字符串的时候也是用的字符。