您的位置:首页 > 移动开发 > Android开发

android关于"记住密码"数据回显的处理

2017-02-06 16:57 351 查看
最近几天刚学android,看到了这里感觉挺有意思的,就写出来分享下,请多指教。

采用最简单的布局:一个用户名框,一个密码框,一个复选框(记住密码),一个登录按钮。

这里的数据我是存储在本地文件,也可以存进数据库,原理都一样。

首先判断复选框是否是选中状态,如果选中,那么把输入的数据就保存下来,如果没有选中则直接进行匹配登录

这里用到了Context(上下文),这样对于android下存储文件提供了很方便的API

上代码:

public static boolean saveData(Context context, String username, String password) {

//通过输出流进行保存文件

File file = new File(context.getFilesDir(), "info.txt");

FileOutputStream out = null;
try {
out  = new FileOutputStream(file);

//这里为了测试方便,我用两个##来进行区分,前边是用户名,后面是密码

out .write((username + "##" + password).getBytes());

return true;
} catch (Exception e) {

return false;

} finally {

try {

fs.close();
} catch (IOException e) {
e.printStackTrace();
}

}

}

这样就把文件保存下来了,接下来,当我们打开这个应用程序的时候,我们就把info.txt里面保存的数据回显到相应的控件里面。

这里我专门写一个用来回显数据的方法:

//这里的返回类型我采用了Map集合

public static Map<String, String> getEchoData(Context context) {

FileInputStream in = null;

BufferedReader read = null;

File file = new File(context.getFilesDir(), "info.txt");

try {

in = new FileInputStream(file);

read = new BufferedReader(new InputStreamReader(in));

String readLine = read.readLine();

//由于前面是用##来区分username和password,这里就用##来进行分割
String[] split = readLine.split("##");

Map<String, String> map = new HashMap<String, String>();

//把分割后的字符串分别放在map集合里面
map.put("username", split[0]);

map.put("password", split[1]);

//最后再返回这个集合
return map;

} catch (Exception e) {

}
return null;

}

最后,我们再在MainActivity的onCreate方法里面,进行设置就完成了:

我们先得到回显数据的函数:

Map<String, String> data = LoginServer.getEchoData(MainActivity.this);

//如果map为null,就说明没有要回显的数据,不为null,就进行回显

if (data != null) {

//设置用户名和密码控件的text为对应的map集合里的数据

usernameEditText.setText(data.get("username"));

passwordEditText.setText(data.get("password"));
}

=======================分割线============================

第一次写,请多多指教,一起学习,一起进步。谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐