Junior — Middle
How can instances of custom classes be saved on a physical device?
sobes.tech AI
Answer from AI
To save instances of custom classes on a physical device in Android, object serialization into a format that can be written to a file or SharedPreferences is usually used. Main methods:
-
Serializable — a standard Java interface for object serialization. Simple but less efficient.
-
Parcelable — an Android-specific interface, faster and optimized for data transfer between components and storage.
-
Saving in JSON or XML — converting the object into a string using libraries (e.g., Gson, Moshi), then writing to a file or SharedPreferences.
Example with Gson:
data class User(val name: String, val age: Int)
val user = User("Ivan", 30)
val gson = Gson()
val json = gson.toJson(user)
// Save json to a file or SharedPreferences
When loading from a file or SharedPreferences, JSON can be deserialized back into an object.