kotlin
Copy
dependencies {
implementation 'com.google.code.gson:gson:2.10.1'
}
kotlin
Copy
data class Recipe(
val name: String,
val ingredients: List<String>,
val instructions: String,
val preparationTime: Int
)
kotlin
Copy
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class MainActivity : AppCompatActivity() {
private val sharedPrefFile = "RecipeBookPrefs"
private lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sharedPreferences = getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE)
// Example usage
val recipe1 = Recipe("Pasta Carbonara", listOf("Spaghetti", "Eggs", "Bacon", "Parmesan"), "Cook pasta...", 30)
val recipe2 = Recipe("Chicken Stir Fry", listOf("Chicken", "Vegetables", "Soy Sauce"), "Cut chicken...", 25)
saveRecipe(recipe1)
saveRecipe(recipe2)
val allRecipes = getAllRecipes()
println("All Recipes: $allRecipes")
updateRecipe(recipe2.copy(preparationTime = 20))
val updatedRecipes = getAllRecipes()
println("Updated Recipes: $updatedRecipes")
deleteRecipe(recipe1.name)
val remainingRecipes = getAllRecipes()
println("Remaining Recipes: $remainingRecipes")
}
private fun saveRecipe(recipe: Recipe) {
val gson = Gson()
val json = gson.toJson(recipe)
val editor = sharedPreferences.edit()
editor.putString(recipe.name, json)
editor.apply()
}
private fun getRecipe(name: String): Recipe? {
val json = sharedPreferences.getString(name, null)
return if (json != null) {
Gson().fromJson(json, Recipe::class.java)
} else null
}
private fun getAllRecipes(): List<Recipe> {
val gson = Gson()
return sharedPreferences.all.mapNotNull { (_, value) ->
if (value is String) {
gson.fromJson(value, Recipe::class.java)
} else null
}
}
private fun updateRecipe(recipe: Recipe) {
saveRecipe(recipe) // Overwrites the existing recipe
}
private fun deleteRecipe(name: String) {
val editor = sharedPreferences.edit()
editor.remove(name)
editor.apply()
}
}