public class loginServe {
public static boolean saveUserInfo(Context context,String username,String password){
try {
File file = new File(context.getFilesDir(),"info.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write((username+"##"+password).getBytes());
fos.close();
return true;
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
return false;
}
}
//获取保存的数据
public static Map, String> getSaveUserInfo(Context context){
File file = new File(context.getFilesDir(),"info.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String str = br.readLine();
String[] infos = str.split("##");
Map, String> map = new HashMap,String>();
map.put("username", infos[0]);
map.put("password", infos[1]);
return map;
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
return null;
}
}
}
这是封装的一个保存数据的类
public class MainActivity extends Activity {
private static final String Tag = "MainActivity";
private EditText et_name;
private EditText et_password;
private CheckBox cb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_password = (EditText) findViewById(R.id.et_psw);
cb = (CheckBox) findViewById(R.id.cb_remeber_name);
Map, String> map = loginServer.getSaveUserInfo(this);
if(map!=null){
et_name.setText(map.get("username"));
et_password.setText(map.get("password"));
}
}
//登录点击事件
public void login(View view){
String username = et_name.getText().toString().trim();
String password = et_password.getText().toString().trim();
if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)){
Toast.makeText(this, "用户名或者密码不能为空", Toast.LENGTH_SHORT).show();
}else {
//判断是否保存密码
if (cb.isChecked()) {
//保存用户密码
Log.i(Tag, "需要保存用户名密码");
boolean result = loginServer.saveUserInfo(this,username,password);
if(result){
Toast.makeText(this, "保存数据成功", Toast.LENGTH_SHORT).show();
}
}
//登录
if("wangzhixin".equals(username)&&("123".equals(password))){
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
}
}
}
}