我正在尝试使用getDefaultSharedPreferences,因为我只有3-4位的布尔数据要保存(第一个应用程序),根据它需要的文档…
"getDefaultSharedPreferencesName (上下文上下文)“
因此,通过深入研究上下文文档,我认为我需要提供的所有内容都是上下文,因为这将是我片段的上下文,所以我尝试
val sharedPref: SharedPreferences = getDefaultSharedPreferences(Context)
然而,我得到了错误
“分类器'Context‘没有伴生对象,因此必须在这里初始化”。
在谷歌上搜索一下,似乎没有太多getDefaultSharedPreferences的例子。有人能帮上忙吗?
发布于 2020-10-25 17:13:41
您在问题中发布的代码行的问题在于,您传递的不是context
值,而是Context
类型。请确保使用带有小写“c”的上下文
- val sharedPref: SharedPreferences = getDefaultSharedPreferences(Context)
+ val sharedPref: SharedPreferences = getDefaultSharedPreferences(context)
发布于 2020-10-25 17:10:18
如果您正在使用片段,请使用getActivity()
作为上下文。
发布于 2020-10-25 17:19:44
为了提供SharedPreferences
,最好使用Application
上下文。你应该在你的应用中使用Application
类的contex。
https://stackoverflow.com/questions/64522031
复制相似问题