Android - How to use SharedPreferences in non-Activity class?

后端 未结 12 2375
日久生厌
日久生厌 2020-12-13 08:54

How do you use SharedPreferences in a non-Activity class? I tried making a generic Preferences utility class and importing android.content.Context but Eclipse s

12条回答
  •  误落风尘
    2020-12-13 09:12

    In Kotlin you can do this:

    val myClass = MyClass(this)
    

    Now this is how you can get context in class

    class MyClass(context: Context) {
    
        val context: Context = context
    
    }
    

    Now to get Shared Preferences with context you can do this:

    context.getSharedPreferences(...)
    

提交回复
热议问题