安卓 使用SharedPreferences存储在哪了
时间: 2024-05-21 13:11:16 浏览: 14
SharedPreferences 存储在 Android 应用程序的默认存储位置中,具体位置取决于应用程序的包名和数据类型。一般来说,SharedPreferences 存储在应用程序的数据目录下的 shared_prefs 文件夹中。例如,如果应用程序的包名为 com.example.myapp,则其 SharedPreferences 存储位置为 /data/data/com.example.myapp/shared_prefs/。可以使用 Context.getSharedPreferences() 方法来获取 SharedPreferences 对象,并使用 SharedPreferences.Editor 来编辑和保存数据。
相关问题
android sharedpreferences 保存list,使用SharedPreferences存储List<T>
可以使用Gson将List<T>序列化为json字符串,然后再将json字符串存储到SharedPreferences中。
示例代码:
```java
// 将List<T>转换成json字符串
Gson gson = new Gson();
String json = gson.toJson(list);
// 将json字符串保存到SharedPreferences中
SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();
editor.putString("my_list", json);
editor.apply();
```
获取List<T>时,将json字符串反序列化为List<T>对象即可。
示例代码:
```java
// 获取存储的json字符串
SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
String json = prefs.getString("my_list", "");
// 将json字符串反序列化为List<T>
Gson gson = new Gson();
Type type = new TypeToken<List<T>>() {}.getType();
List<T> list = gson.fromJson(json, type);
```
其中,T表示要保存的对象类型。需要注意的是,要保证该对象类型是可序列化的。如果该对象类型中包含自定义对象类型,则需要自定义序列化和反序列化方法。
如何使用SharedPreferences存储
和读取数据?
SharedPreferences是Android系统提供的轻量级数据存储方式,可以用于存储键值对数据,比如应用的配置参数、用户登录状态等。使用SharedPreferences存储数据,可以通过以下步骤:
1. 获取SharedPreferences对象
SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
其中,第一个参数是SharedPreferences的名称,第二个参数是访问模式,MODE_PRIVATE表示只有当前应用可以访问。
2. 存储数据
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "Tom");
editor.putInt("userAge", 20);
editor.apply();
其中,putString()方法用于存储字符串类型的数据,putInt()方法用于存储整型数据,apply()方法用于提交数据的修改。
3. 读取数据
String userName = sharedPreferences.getString("userName", "");
int userAge = sharedPreferences.getInt("userAge", 0);
其中,getString()方法用于读取字符串类型的数据,getInt()方法用于读取整型数据,第二个参数是默认值,表示在SharedPreferences中不存在该键时返回的默认值。
注意,存储和读取数据的过程必须在同一个SharedPreferences对象中完成。同时,存储的数据类型必须与读取的数据类型一致。
相关推荐
![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)