在Kotlin中使用共享首选项检索值

时间:2018-10-21 19:11:10

标签: android kotlin

我试图在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)
    }
}

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您需要致电commit,即

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

答案 2 :(得分:0)

Class MyPreference(context:Context) {

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()
}

}

答案 3 :(得分:0)

由于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) {
  ...

仅在实例化时提供上下文。