Android数据存储——SharedPreferences

一、使用SharedPreferences存储数据的步骤

使用SharedPreferences存储数据的步骤

二、使用SharedPreferences读取数据的步骤

使用SharedPreferences读取数据的步骤

接下来我们通过一个实例来熟悉、理解、掌握SharedPreferences

创建两个页面即两个Activity

第一个页面为登录页面,三个控件:一个username编辑框,一个password编辑框,一个登录按钮。

第二个页面自定义。(记得在Manifest里面注册)

实现功能:第一次输入后台定义好的用户名和密码,则跳转到第二个页面;否则登陆失败。如果第一次登录成功,之后进入此应用,就不用输入用户名和密码,它会直接跳转到第二个页面。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText editText = findViewById(R.id.editText);
        EditText editText2 = findViewById(R.id.editText2);
        Button button = findViewById(R.id.button);
        
		//获取SharedPreferences对象
        SharedPreferences sp = getSharedPreferences("login",MODE_PRIVATE);
        
        //给sp里面放置默认数据(键值对的方式)
        String username = sp.getString("username",null);
        String password = sp.getString("password",null);
        
        //如果username和password是admin、123456,则直接跳转到第二个页面
        if(username!=null && password!=null) {
            if (username.equals("admin") && password.equals("123456")) {
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            }
        }else{   //否则给button设置监听器
           button.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   String Input_username = editText.getText().toString();
                   String Input_password = editText2.getText().toString();

                   SharedPreferences.Editor editor = sp.edit();       //获取editor对象

             //如果输入的用户名和密码为admin、123456则将用户名和密码放到editor里面,并将editor进行提交,并跳转到第二个页面
                   if (Input_username.equals("admin") && Input_password.equals("123456")) {
                       editor.putString("username", Input_username);
                       editor.putString("password", Input_password);
                       editor.commit();
                       Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                       startActivity(intent);
                       Toast.makeText(MainActivity.this, "用户名和密码已经保存", Toast.LENGTH_SHORT).show();
                   } else {
                       Toast.makeText(MainActivity.this, "用户名和密码错误", Toast.LENGTH_SHORT).show();
                   }

               }
           });
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值