package com.example.settingsapp
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class SettingsActivity : AppCompatActivity() {
private lateinit var usernameEditText: EditText
private lateinit var saveButton: Button
private lateinit var savedUsernameTextView: TextView
private lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
usernameEditText = findViewById(R.id.usernameEditText)
saveButton = findViewById(R.id.saveButton)
savedUsernameTextView = findViewById(R.id.savedUsernameTextView)
sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
// Load saved username and display it
val savedUsername = sharedPreferences.getString("username", null)
if (savedUsername != null) {
savedUsernameTextView.text = savedUsername
} else {
savedUsernameTextView.text = "No username saved"
}
// Save username on button click
saveButton.setOnClickListener {
val username = usernameEditText.text.toString()
if (username.isNotBlank()) {
sharedPreferences.edit().putString("username", username).apply()
savedUsernameTextView.text = username
}
}
}
}This code uses SharedPreferences to save and load a username.
When the screen opens, it reads the saved username from SharedPreferences. If there is one, it shows it; otherwise, it shows a default message.
When the user types a username and taps Save, the app saves the username in SharedPreferences and updates the displayed saved username immediately.
This way, the username stays saved even if the app is closed and reopened.