import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
//1)点击登录按钮,完成输入的用户名、密码的非空校验
//2)将用户名,登录状态缓存到SharedPreferences,
//3)登录成功之后下次不再进入登录页面,直接进入图三所示主页面
private EditText edit_name,edit_pwd;
private Button btn_login;
private SharedPreferences sharedPreferences;
private Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//获取资源ID
edit_name = (EditText) findViewById(R.id.edit_name);
edit_pwd = (EditText) findViewById(R.id.edit_pwd);
btn_login = (Button) findViewById(R.id.btn_login);
sharedPreferences = getSharedPreferences("User", MODE_PRIVATE);
editor = sharedPreferences.edit();
boolean succ = sharedPreferences.getBoolean("succ", false);
if(succ){
Intent intent1 = new Intent(LoginActivity.this, SuccessActivity.class);
startActivity(intent1);
finish();
}
btn_login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = edit_name.getText().toString();
String pwd = edit_pwd.getText().toString();
Toast.makeText(LoginActivity.this, name, 0).show();
if(name.equals("") || pwd.equals("")){
Toast.makeText(LoginActivity.this, "用户名或密码错误", 0).show();
}else{
Intent intent1 = new Intent(LoginActivity.this, SuccessActivity.class);
startActivity(intent1);
Toast.makeText(LoginActivity.this, "登陆成功", 0).show();
editor.putBoolean("succ", true);
editor.putString("name", name);
editor.commit();
}
}
});
}
}
sharedPerference登录保存密码
最新推荐文章于 2023-08-28 19:18:55 发布
本文介绍如何在Android应用中利用SharedPreferences组件持久化保存用户的登录状态和密码,确保用户在下次打开应用时能直接进入已登录状态,提高用户体验。
摘要由CSDN通过智能技术生成