Simple use of SharedPreferences for android-data storage (remember the password)

Today, I will use SharedPreferences to realize the function of remembering the password. When the user checks the remember password, the login account password box is automatically filled in

1. xml layout, not described here
2. main file operation
(1), get SharedPreferences object The
first parameter is the file name of the stored data, and the second data is the storage method

SharedPreferences mysp = getSharedPreferences("mysp", MODE_PRIVATE);

(2) Realize password saving.
When the login button is clicked, it is judged whether the remember password box is checked. If the remember password check box is checked, save the content of the input box
to a SharedPreferences.Editor object
through the putString of the object The method realizes the save Save
by the key-value pair.
Finally, remember to submit it, otherwise it will be invalid

 btn_login.setOnClickListener(v -> {
    
    
            if (cb_rember.isChecked()){
    
    
                SharedPreferences.Editor edit = mysp.edit();
                edit.putString("username", uname.getText().toString().trim());
                edit.putString("password", upass.getText().toString().trim());
                edit.commit();
            }
        });

(3) Realize to read the data
. After saving the data, it will be automatically read after logging in. The key is read
through the getstring method of the SharedPreferences object, and the same type of data is returned. The
edit box gets the read data

		String username = mysp.getString("username", null);
        String password = mysp.getString("password", null);
        uname.setText(username);
        upass.setText(password);

3. Results
Insert picture description here
PS: This method can be used to perform the logic of displaying the guide page when the user logs in for the first time. The user-defined value is saved when the user logs in for the first time. If there are saved values ​​after logging in, the user guide page can be skipped. There may be notes in the future

Guess you like

Origin blog.csdn.net/Willow_Spring/article/details/112997040