0

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?)

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Jim Peng
  • 9
  • 2

3 Answers3

0

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

Kushal
  • 8,100
  • 9
  • 63
  • 82
0

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
  }
Sajjad Javed
  • 139
  • 2
  • 14
0

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.

easy_breezy
  • 1,073
  • 7
  • 18