android-如何在SharePreferences中存储Set>?

android-如何在SharePreferences中存储Set>?,第1张

概述我在项目中使用SharedPreference.我知道sharedPreference可以存储Set<String>通过使用prefs.putStringSet().但是我有一种情况需要存储Set<Set<String>>.在sharedPreference中.我该如何实现?解决方法:您可以使用Gson转换Set<Set<String>>字符串然后将其保存在sharepreference

我在项目中使用SharedPreference.

我知道sharedPreference可以存储Set< String>通过使用prefs.putStringSet().但是我有一种情况需要存储Set< Set< String>>.在sharedPreference中.

我该如何实现?

解决方法:

您可以使用Gson转换Set< Set< String>>字符串然后将其保存在sharepreference中,但是没有直接的方法将这种类型保存在sharepreference中

Gson gson = new Gson();    String JsonObject = gson.toJson(your_set_variable);    editor.putString(KEY_PROJECTS, JsonObject );    editor.commit();

更新 :
这是Google的Gson库,如果您需要使用它,请将其添加到gradle依赖项中

compile 'com.Google.code.gson:gson:2.8.0'

这个库为您提供了将任何对象转换为字符串,然后将该Json字符串转换为您想要的类型的方法,stackoverflow和Google有很多使用它的示例

总结

以上是内存溢出为你收集整理的android-如何在SharePreferences中存储Set>?全部内容,希望文章能够帮你解决android-如何在SharePreferences中存储Set>?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1081050.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存