Android – SharedPreferences – 上下文
我想在android中使用kotlin为我的SharedPreference
创建一个辅助类。 不幸的是,我需要Context
,我不希望每次调用一个首选项时将其设置为参数。
如果我使用上下文的伴侣对象,并将其设置在应用程序启动,我得到以下错误: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
那么如何获得上下文,而不是每次调用偏好时都通过它?
var isWorking: Boolean get() = getBoolean(IS_WORKING) set(isWorking) = setPreference(IS_WORKING, isWorking) private fun setPreference(key: String, value: Boolean) { val editor = settings.edit() editor.putBoolean(key, value) editor.commit() } private val settings: SharedPreferences by lazy { context.getSharedPreferences("prefs", Context.MODE_PRIVATE) }
您可以创建一个extension function
如下所示:
object PreferenceHelper { fun defaultPrefs(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) fun customPrefs(context: Context, name: String): SharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE) inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) { val editor = this.edit() operation(editor) editor.apply() } }
编辑: 这是这个答案的参考。 您可以检查如何使用Kotlin
技巧来重构util classes
并使用它。
EDIT2:
你可以改变你的帮手类,并在你的Application
初始化。 那么你可以使用任何你想要的。 我认为这是你想要做的。 我们开始做吧。
class PreferenceHelper constructor(context: Context){ fun defaultPrefs(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) fun customPrefs(name: String): SharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE) inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) { val editor = this.edit() operation(editor) editor.apply() } }
并在您的应用程序类:
class YourApp : Application() { override fun onCreate() { super.onCreate() YourApp.prefHelper = PreferenceHelper(this) } companion object { lateinit var prefHelper: PreferenceHelper private set } }
你可以使用任何你想要的地方如下:
YourApp.prefHelper.defaultPrefs().edit { // Your shared pref operations. }
我认为第一个更接近最佳实践,但第二个也是可以的。 你可以使用你需要的一个。 此外,我在上面提供的链接内容中还有更酷的例子。
我find了解决我的问题。 我通过持久化SharedPreferences
variables而不是上下文来解决它。
object PreferenceDao { private lateinit var settings: SharedPreferences fun init(context: Context) { settings = context.getSharedPreferences("prefs", Context.MODE_PRIVATE) } }
init函数在我的Application
类中被调用。
- Kotlin的@Parcelize在writeToParcel()上抛出NPE
- ResourceNotFoundException在升级到Canary 6后,在API 16 AVD上运行Kotlin项目