【问题标题】:Retrieving Value using Shared Preference in Kotlin在 Kotlin 中使用共享偏好检索值
【发布时间】:2018-10-21 19:11:09
【问题描述】:

我试图在 kotlin 中的两个活动之间传递一个值,但如果我使用下面的代码,那么我只会得到“Hello World”默认值,而不是 PREFERENCE_NAME 值。我的文本 id 名称是 android:id="@+id/tv_count" 任何帮助表示赞赏。

Main Activity:
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val mypreference=MyPreference(this)
        var loginCount=mypreference.getLoginName()
        mypreference.setLoginName(loginCount)
        tv_count.text=loginCount.toString()
    }
}

My Preference:
import android.content.Context

class MyPreference(context:Context)
{

    val PREFERENCE_NAME="SharedPreferenceExample"
    val preference=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE)

    fun getLoginName():String
    {
        return preference.getString(PREFERENCE_NAME,"Hello World")
    }

    fun setLoginName(name:String)
    {
        val editor=preference.edit()
        editor.putString(PREFERENCE_NAME,name)
    }
}

【问题讨论】:

标签: android kotlin


【解决方案1】:

在您的情况下,您没有使用 editor.commit() 函数。这是整个代码

//Store in SharedPreference  
 val preference=getSharedPreferences(resources.getString(R.string.app_name), Context.MODE_PRIVATE)
    val editor=preference.edit()
    editor.putBoolean("isLoggedIn",true)
    editor.putInt("id",1)
    editor.putString("name","Alex")
    editor.commit()


//Retrieve from SharedPreference

    val name= preference.getString("name","")
    val id= preference.getInt("id",0)
    val isLoggedIn= preference.getBoolean("isLoggedIn",false)

【讨论】:

  • 感谢您的建议!
【解决方案2】:

您需要致电commit,即

fun setLoginName(name:String)
{
    val editor=preference.edit()
    editor.putString(PREFERENCE_NAME,name)
    editor.commit()
}

【讨论】:

  • 感谢 John O'Reily 的回复。我仍然在屏幕上看到 Hello World
【解决方案3】:

这将是一个更广泛的答案,展示了一种非常优雅地使用首选项的一般方式,这要归功于 Kotlin 中的委托属性。这些使我们能够为日常资产提供我们自己的后备存储。

考虑这个描述如何读取和写入布尔值的类:

class BooleanPrefStore(val default: Boolean = false) {
  operator fun getValue(thisRef: ContextWrapper?, property: KProperty<*>): Boolean =
    PreferenceManager.getDefaultSharedPreferences(thisRef)
      .getBoolean(property.name, default)

  operator fun setValue(thisRef: ContextWrapper?, property: KProperty<*>, value: Boolean) {
    PreferenceManager.getDefaultSharedPreferences(thisRef)
      .edit()
      .putBoolean(property.name, value)
      .apply()
  }
}

一个 getter 和一个 setter 使用通常的方式从首选项中读取和写入。通过这个类,我们可以非常简洁优雅地设置我们的属性:

var Property1: Boolean by BooleanPrefStore()
var Property2: Boolean by BooleanPrefStore(true)

它甚至允许我们提供一个默认值,如果它不同于“默认默认值”。如果需要,只需以相同的方式创建其他帮助程序类,IntPrefStoreLongPrefStoreStringPrefStore。然后,您只需使用这些属性或为它们分配值,所有这些都将自动存储到首选项存储并从首选项存储中检索。

只有一个警告:偏好存储需要访问当前上下文。如果您在 ActivityFragment 或类似的保留上下文的 Android 类中声明这些属性,则您无事可做。所有这些类都实现了ContextWrapper。但是如果您需要自己的类中的属性,则需要自己将其设为ContextWrapper,例如:

class MyClass private constructor(context: Context) : ContextWrapper(context) {
  ...

只需在实例化时提供上下文即可。

【讨论】:

    【解决方案4】:

    在 Kotlin 中使用 SharedPreferences 的简单方法

    创建对象首选项{}

    object Preference {
    private const val NAME = "pig"
    private const val MODE = Context.MODE_PRIVATE
    private lateinit var preferences: SharedPreferences
    private val REFER_CODE = Pair("refer_code", "")
    
    fun init(context: Context) {
        preferences = context.getSharedPreferences(NAME, MODE)
    }
    
    private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
        val editor = edit()
        operation(editor)
        editor.apply()
    }
    
    var referCode: String
        get() = preferences.getString(REFER_CODE.first, REFER_CODE.second).toString()
        set(value) = preferences.edit {
            it.putString(REFER_CODE.first, value)
        }
       }
    

    在应用程序类中初始化

    class App : Application() {
    
    
    override fun onCreate() {
        super.onCreate()
      
        Preference.init(this)
    
       }
    

    并在您的片段或活动中使用:

     Preference.referCode = "working" // Set value in preference
     Timber.d(Preference.referCode)  // Get value
    

    【讨论】:

      【解决方案5】:

      类我的偏好(上下文:上下文) {

      val PREFERENCE_NAME="SharedPreferenceExample"
      val preference=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE)
      
      fun getLoginName():String
      {
          return "$PREFERENCE_NAME"
      }
      
      fun setLoginName(name:String)
      {
          val editor=preference.edit()
          editor.putString(PREFERENCE_NAME,name)
          editor.commit()
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-30
        • 1970-01-01
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多