SharedPreferences跳转界面保存数据
时间: 2023-08-30 09:12:25 浏览: 69
可以使用 SharedPreferences 在一个 Activity 中保存数据,然后在另一个 Activity 中获取这些数据并展示。具体步骤如下:
1. 在第一个 Activity 中,创建一个 SharedPreferences 对象,并使用其 edit() 方法来获取一个 SharedPreferences.Editor 对象。
2. 在 SharedPreferences.Editor 对象中使用 putXXX() 方法来存储数据,其中 XXX 表示数据类型,如 putString()、putInt() 等。
3. 调用 SharedPreferences.Editor 对象的 apply() 或 commit() 方法来提交数据。
4. 在第二个 Activity 中,使用 getSharedPreferences() 方法来获取之前保存的 SharedPreferences 对象。
5. 使用 SharedPreferences 对象的 getXXX() 方法来获取之前存储的数据。
6. 在界面上展示获取到的数据。
下面是一个示例代码:
在第一个 Activity 中:
```
// 创建 SharedPreferences 对象
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
// 获取 SharedPreferences.Editor 对象
SharedPreferences.Editor editor = sharedPreferences.edit();
// 存储数据
editor.putString("name", "Tom");
editor.putInt("age", 18);
// 提交数据
editor.apply();
```
在第二个 Activity 中:
```
// 获取之前保存的 SharedPreferences 对象
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
// 获取数据并展示
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 0);
textView.setText("Name: " + name + ", Age: " + age);
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)