ccd
ccd

Reputation: 6908

ViewModel using SharedPreference to store variable

I create a object to using sharedPreference.

private const val PREF_LOGIN_NAME = "loginName"

object LoginPreferences {

    fun getStoredName(context: Context): String {
        val prefs = PreferenceManager.getDefaultSharedPreferences(context)
        return prefs.getString(PREF_LOGIN_NAME, "testExample")!!
    }

    fun setStoredName(context: Context, query: String) {
        PreferenceManager.getDefaultSharedPreferences(context)
            .edit()
            .putString(PREF_LOGIN_NAME, query)
            .apply()
    }
}

Then I using this object with my ViewModel.

class LoginViewModel(private val app: Application) : AndroidViewModel(app) {

    val name: String
        get() = LoginPreferences.getStoredName(app)

    fun loginSubmit() {
        LoginPreferences.setStoredName(app, name)
    }
}

The LoginViewModel is success binding in my LoginFragment.

But if I want to persistent save this to sharedPreference, the code I show in LoginViewModel is not work for me.

Upvotes: 0

Views: 411

Answers (1)

Christilyn Arjona
Christilyn Arjona

Reputation: 2283

The second parameter in the prefs.getString(...) method represents a default value, not the value itself.

prefs.getString(PREF_LOGIN_NAME, "testExample") means that if your shared preferences could not find the value associated with the specified key (PREF_LOGIN_NAME), it will return the default value instead - which is "testExample"

See https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)

If you want to clear your shared preferences, you can do:

prefs.edit().clear().apply()

Then, if you call getStoredName(...) for the first time, you will get testExample as a result (assuming you don't call setStoredName(...) before this).

Upvotes: 1

Related Questions