Search code examples
androidkotlinsharedpreferences

How to save an object in sharedPreferences and then shown in the favorite fragment in Android using Kotlin?


I have the following data class, which shows a list of movies in a recyclerView, when the user clicks on a movie it goes to the detail which have a favorite button, and when it clicks on the favorite button it gets saved and shown in a Favorites fragment tab, I want this list to persist app launches. Using Kotlin.

data class MovieItem(
    @SerializedName("id")
    val id: Int,
    @SerializedName("image")
    val image: Image,
    @SerializedName("name")
    val name: String,
    @SerializedName("summary")
    val summary: String
):Serializable

I saw somewhere else to save it as gson object, but I'm not sure how to retrieve it to show it in the favorites fragment:

in the detailViewModel I converted it to json:

fun convertToJson(movie: MovieItem) {
    val json = Gson().toJson(movie)
 }

in the favoritesViewModel:

fun getFavorites(json:String) {
    val json = Gson().fromJson(json, MovieItem.class)
}

Solution

  • This is For Insert In SharedPreferences

        val movieItem = MovieItem(id, image, name,summary)
        
        val gsonObject = Gson()
        
        val movieToJson = gsonObject.toJson(movieItem)
        
        sharedPrefs.edit().putString(id, movieToJson).apply()
    

    This For Retrieve

    sharedPrefs.edit().getString(firebaseID,"//Defult If not Found Any thing for this id").apply()
    

    Above Line returns you to the specific movie if you want all then you need to collect all the present movies Key of sharedPref below link help you to find out

    Find All SharedPreferences Keys then you can use for loop to get all thevalue using my retrieve code and add the value inside the list and then show it in the fragment. i hope its helpful for you.