使用SharedPreferences保存输入的用户名和密码
时间: 2024-05-06 10:15:21 浏览: 23
好的,以下是一个简单的实现:
```java
// 保存用户名和密码
SharedPreferences sharedPreferences = getSharedPreferences("userInfo", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "your_username");
editor.putString("password", "your_password");
editor.apply();
// 获取保存的用户名和密码
SharedPreferences sharedPreferences = getSharedPreferences("userInfo", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
String password = sharedPreferences.getString("password", "");
```
在这个例子中,我们使用了一个名为 "userInfo" 的 SharedPreferences 对象来保存用户名和密码。我们首先获取 SharedPreferences 的实例,并通过 edit() 方法创建一个 SharedPreferences.Editor 对象。然后,我们使用 putString() 方法将用户名和密码存储在 SharedPreferences 对象中,并使用 apply() 方法将更改提交给 SharedPreferences 对象。
要获取保存的用户名和密码,我们只需要在 SharedPreferences 对象上调用 getString() 方法,并将键名作为第一个参数,如果该键不存在,我们可以提供一个默认的空字符串作为第二个参数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)