I am quite new to Android Studio, and for a study project, I am creating an app that uses Kotlin, Compose and Navigator. I want to store data from a form as key-value pairs in SharedPreferences, but although I have found an example how to do it in Compose, this was not using navigator, and I haven’t been able to figure out where to initialize the variables with the navigator structure, can someone help me with that?
In the example, these variables are initiated at the start of MainActivity.kt:
class MainActivity : ComponentActivity() {
lateinit var sharedPreferences: SharedPreferences
var PREFS_KEY = "prefs"
var EMAIL_KEY = "email"
var PWD_KEY = "pwd"
var e = ""
var p = ""
and then within setContent, shared preferences is initialized:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
In my case with the navigator structure, I have tried placing the variables either in the MainActivity file, as well as within the navigator fragment where I want to store the values. If I place it in the MainActivity, the sharedPreference variable is not known in the navigator fragment, and when I place it in the main function of the navigator fragment, the line: sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE) gives me the error: Unresolved reference: getSharedPreferences (I have included import android.content.SharedPreferences in both files)
CodePudding user response:
To use SharedPreferences to store form data in an Android app that uses Kotlin, Compose and Navigator, you need to create a SharedPreferences object in your MainActivity.kt file. Then use the object to store your form data using the putString() and getString() methods. Then, in your navigator fragment, you can access your SharedPreferences object using the getSharedPreferences() method. Then you can use the getString() and putString() methods to access and store the data.
See the example:
In MainActivity.kt:
val sharedPreferences = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
In NavigatorFragment.kt:
val sharedPreferences = activity?.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE)
// To store data
sharedPreferences?.edit { putString("name", name) }
// To retrieve data
val name = sharedPreferences?.getString("name", "")