Reputation: 1
I'm completely new to Kotlin and i want to make an application where by pressing a button we will get a new text showing on a textview. The problem is that there is suppose to be like 365 sentences and i'm not sure if the arraylist is the best way of doing this.
I'd managed to save the text to sharedpreferences but everytime when i open the app again, the proper text is showing but after clicking a button it's again starting from the beginning
fun loadData() {
val sharedPreferences = getSharedPreferences("SP_INFO", Context.MODE_PRIVATE)
val someText = sharedPreferences.getString("SOME_TEXT", "")
selectedSomeText.text = "$someText"
}
fun saveData() {
val sharedPreferences = getSharedPreferences("SP_INFO", Context.MODE_PRIVATE)
val someText = selectedSomeText.text.toString().trim()
val editor = sharedPreferences.edit()
editor.putString("SOME_TEXT", someText)
editor.apply()
}
I expect that after every button click the text will just go to another index of the array and I want my app to remember on which index it was before closing the app and to just go further while again clicking and clicking it.
Upvotes: 0
Views: 302
Reputation: 133
If you need to keep track of the position in the array, it might make more sense to only save the position (Int) to your Shared Preferences, and set your current index in the array to that integer when you load your application again.
Something like this might work (Note: I'm not sure if this is exactly what your setup looks like so I'm guessing at the structure here)
val stringsArray: Array<String> = arrayOf(...)
var currentPosition = 0
fun loadData() {
val sharedPreferences = getSharedPreferences("SP_INFO", Context.MODE_PRIVATE)
val lastPosition = sharedPreferences.getInt("STRING_ARRAY_POSITION", 0)
currentPosition = lastPosition
selectedSomeText.text = stringsArray[lastPosition]
}
fun saveData() {
val sharedPreferences = getSharedPreferences("SP_INFO", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putInt("STRING_ARRAY_POSITION", currentPosition)
editor.apply()
}
Upvotes: 1