Reputation:
I am trying to pass a value between two activities in kotlin but if I used the below code then I am getting only "Hello World" default value and not the PREFERENCE_NAME value. My text id name is android:id="@+id/tv_count" Any help is appreciated.
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)
}
}
Upvotes: 5
Views: 7753
Reputation: 701
Easy way of using SharedPreferences in Kotlin
Create an object Preference{}
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)
}
}
Initialize in application class
class App : Application() {
override fun onCreate() {
super.onCreate()
Preference.init(this)
}
And use in your Fragment or activity:
Preference.referCode = "working" // Set value in preference
Timber.d(Preference.referCode) // Get value
Upvotes: 0
Reputation: 10224
This one will be a broader answer showing a general way of using preferences very elegantly, thanks to the delegated properties in Kotlin. These allow us to provide our own backing store to everyday properties.
Consider this class that describes how to read and write a boolean:
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()
}
}
A getter and a setter that uses the usual way to read and write from the preferences. And with this class, we can set up our properties very concisely and elegantly:
var Property1: Boolean by BooleanPrefStore()
var Property2: Boolean by BooleanPrefStore(true)
It even allows us to supply a default value, if it's different from the "default default value". Just create the other helpers classes the same way, IntPrefStore
, LongPrefStore
or StringPrefStore
, if you need them. And then, you simply use these properties or assign values to them, and all will be stored to and retrieved from the preference store automagically.
Just one caveat: the preference storage needs access to the current context. If you declare these properties in an Activity
, Fragment
or similar Android class that keeps the context, you have nothing else to do. All those classes implement ContextWrapper
. But if you need the properties in your own class, you need to make it a ContextWrapper
yourself, for instance:
class MyClass private constructor(context: Context) : ContextWrapper(context) {
...
Just provide the context when you instantiate it.
Upvotes: 0
Reputation: 330
In your case, you have not used editor.commit() function. Here is the whole code
//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)
Upvotes: 13
Reputation:
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()
}
}
Upvotes: -2
Reputation: 10330
You need to call commit
i.e.
fun setLoginName(name:String)
{
val editor=preference.edit()
editor.putString(PREFERENCE_NAME,name)
editor.commit()
}
Upvotes: 3