Search code examples
androidkotlinpersistencedata-class

Store Custom Kotlin Data Class to disk


I'm having trouble figuring out a good way to do a Favorites list. I have a recycler view with a button to store an item to Favorites, I can easily just store this items id but then I have to remake network calls just to get some basic info to fill the list item view.

Here is a screen shot of my recycler view..

RecyclerView

These items are a simple data class defined as follows

data class CoinListItem(
    @Expose
    @SerializedName("id")
    var id: String? = null,
    @Expose
    @SerializedName("name")
    var name: String? = null,
    @Expose
    @SerializedName("symbol")
    val symbol: String? = null,
    @Expose
    @SerializedName("website_slug")
    val slug: String? = null,
    @Expose
    @SerializedName("quote")
    val quoteItem: CoinListQuoteItem? = null,
    @Expose
    @SerializedName("tags")
    val tags: List<String>? = null): Parcelable

Is there a way to save custom objects to disk?


Solution

  • Yep. You can depict class as Serializable CoinListItem(...): Serializable thus you tell the system that it can be serialized to and deserialized from text. Next - you create File serialize your object by

        val item = CoinListItem()
        val file = FileOutputStream("file.txt") // here should be a full path and name
        val outStream = ObjectOutputStream(file)
    
        // Method for serialization of object
        outStream.writeObject(item)
    
        outStream.close()
        file.close()
    
    

    To deserialize it use

    
        val file = FileInputStream("file.txt")
        val inStream = ObjectInputStream(file)
    
        // Method for deserialization of object
        val item = inStream.readObject() as CoinListItem
    
        inStream.close()
        file.close()
    
    

    Hope it helps.