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();
                   }

               }
           });
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43467892/article/details/117879096