How to save variables after quitting application in Kotlin

kotlin save data
sharedpreferences
how to store multiple values in sharedpreferences in android
sharedpreferences deprecated
how to get data from shared preference in android
kotlin sharedpreferences
android save app settings
android developer save app settings

I'm trying to create a flashcards app in Kotlin but I'm not sure how to make the flashcards I create save after exiting.

val flashCards = FlashCardList(50)
flashCards.addCard(inputTerm.text.toString(),inputDefinition.text.toString(),false)

This above code creates a list of Flashcards (size 50) with term and definition and then adds to it. How would I make this save even after exiting? My understanding from searching is to use sharedpreferences but even after reading some explanations I don't really understand how I would use that here. If someone could turn my above code into one that uses sharedpreferences (or any form of saving variables) I could try to understand what's going on from that.

(This is another post on this forum that I read but couldn't understand in case someone else tries to link it: save variables after quitting application?)

As we need to store custom modals in shared preference, we need to make objects serialisable. Gson is google's library which can do this. Use Gson library first and then :

Storing in shared preference :

val flashCards = FlashCardList(50)
flashCards.addCard(inputTerm.text.toString(),
   inputDefinition.text.toString(),false)
var gson = Gson()

// Convert our object in json string 
var jsonFlashCards = gson.toJson(flashCards);
Log.d("TAG","jsonFlashCards = " + jsonFlashCards);

// store json in shared preference
var appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
var prefsEditor = appSharedPrefs.edit();
prefsEditor.putString("MyObject", jsonFlashCards)
prefsEditor.commit()

Reading from shared preference :

// Get json from shared preference
var appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
var gson = Gson();
var jsonFlashCards = appSharedPrefs.getString("MyObject", "");

// Convert json string to array list
Type type = new TypeToken<List<FlashCardList>>(){}.getType();
List<FlashCardList> carsList = gson.fromJson(jsonFlashCards, type);

To add Gson in your project : Gson library in Android Studio

Reference :

  1. https://stackoverflow.com/a/22019470/1994950

  2. https://stackoverflow.com/a/15011927/1994950

How to save variables after quitting application in Kotlin, As we need to store custom modals in shared preference, we need to make objects serialisable. Gson is google's library which can do this. How to declare a variable in Kotlin? To declare a variable in Kotlin, either var or val keyword is used. Here is an example: var language = "French" val score = 95. The difference in using var and val is discussed later in the article. For now, let's focus on variable declaration. Here, language is a variable of type String, and score is a

You can also use Serialization in position of GSON (just extent you'r class with Serializable), after that you can save & retrieve it, from shared Pref.

fun <T : Serializable?> saveSerializable(
context: Context,
objectToSave: T,
fileName: String?
) {
try {
    val fileOutputStream: FileOutputStream =
        context.openFileOutput(fileName, Context.MODE_PRIVATE)
    val objectOutputStream = ObjectOutputStream(fileOutputStream)
    objectOutputStream.writeObject(objectToSave)
    objectOutputStream.close()
    fileOutputStream.close()
} catch (e: IOException) {
    e.printStackTrace()
}
}

fun <T : Serializable?> readSerializable(
context: Context,
fileName: String?
): T? {
var objectToReturn: T? = null
try {
    val fileInputStream = context.openFileInput(fileName)
    val objectInputStream = ObjectInputStream(fileInputStream)
    objectToReturn = objectInputStream.readObject() as T
    objectInputStream.close()
    fileInputStream.close()
} catch (e: IOException) {
    e.printStackTrace()
} catch (e: ClassNotFoundException) {
    e.printStackTrace()
  }
  return objectToReturn
  }

Use saved values, If you have a relatively small collection of key-values that you'd like to your app settings (although they also use SharedPreferences to save� In Java, we could create a global variable just by defining the variable at the beginning of class declaration and initializing it afterward. By just declaring it, we could use it as a global variable. In this recipe, we will learn how to create and use a global variable in Kotin.

Using shared preferences, you can save the variables that have only primitive types like an integer, string, float, and so on. In your case I would create a class with name for example "FlashCardData" that was store all the data for your FlashCard and create the two methods inside it, the first one will return all it's data as a json string which then you can store in the app's SharedPreferences and the second method (or you can instead create a secondary constructor for the class) that will take a json string with the data for the FlashCard and return an instance of FleshCardData class filled with data from json string. And finally i would pass a FlashCardData class to the FlashCard constructor where then the FlashCard will take all the needed data from it, and also i would create a method inside a FlashCard that will return an istance of FlashCardData that was pass to the FlashCard constructor.

Save key-value data, Ktor is a framework built by JetBrains for creating Web applications in Kotlin, making use of and expertise, saving the e ort for tasks more challenging than implementing While it was already possible to extract this variable just before when , val in when has its during closing the resource after some other exception. Kotlin variables. In Kotlin, declaring a variable is slightly different from that of C, C++ and Java. Either var or val keyword is used for declaring variables. var variable_name:data_type = value; or val variable_name:data_type = value; for example. var x:Int = 10; Here data_type and values are optional.

[PDF] Full Kotlin Reference, Saving textview data when leaving an activity: onPause() or I have a textview in my main activity that I want set to "0" when the app is started the Your problem is that member variables will always be destroyed when the activity is destroyed. This past weekend I published my first ever Android Kotlin Library, The Picker. This example will give you a clear idea of how to make a global variable in kotlin. Step 1. Create a new project “ Build Your First Android App in Kotlin “ Step 2. Create a new class ” MyApplication.kt ” in Kotlin. Extend Application class and add a variable (A android Global Variable)

Saving textview data when leaving an activity: onPause() or , Use shared preferences only when you need to save a small amount data as simple key/value pairs. To manage larger amounts of persistent app data, use a� Coping with Kotlin's Scope Functions. Functions in Kotlin are very important and it's much fun() to use them. One special collection of relevant functions can be described as "scope functions" and they are part of the Kotlin standard library: let, run, also, apply and with.

Android fundamentals 09.1: Shared preferences, Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of its Kotlin variable declarations and parameter lists have the data type come after the variable name When applied to a top-level declaration Kotlin variables. There are two types of variables in Kotlin: read-only and mutable. Read-only variables (or constants) are declared with val and mutable with var. Kotlin data type inference. Kotlin can infer the data type of a variable from the right side of the assignment. The data type is only mandatory when the assignment is deferred.