I am developing an android app for the first time and i am working with Shared Preferences. I wanted to try and use DataStore but i am having an issue where when i press the saveButton after modifying the text in EditText, it would save the value in the datastore, but the activity would close, going back to the previous one.
This is the code:
preferencesActivity.kt:
saveButton.setOnClickListener{
if(editUsername.text.toString().isNotBlank()) {
scope.launch {
preferenceDataStore.changeName(editUsername.text.toString())
}
}
}
SharedPreferences.kt:
class SharedPreferences(context: Context) {
private val pref = context.dataStore
companion object {
val Context.dataStore : DataStore<Preferences> by preferencesDataStore("user_info")
var username = stringPreferencesKey("USERNAME")
}
suspend fun changeName(name: String) {
pref.edit {
it[username] = name
}
}
I have a fairly similar activity where i call the exact same function, but in this case i would not have the same issue.
nameEdit = findViewById(R.id.nameInput)
confirmButton = findViewById(R.id.confirmButton)
confirmButton.setOnClickListener {
if(nameEdit.text.toString().isNotBlank()) {
scope.launch() {
preferenceDataStore.changeName(nameEdit.text.toString().trim())
}
}
}
Dogyyy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.