如何将新地图或行添加到 sharedpreferences 文件

how to add a new map or row to sharedpreferences file

我正在构建一个将数据存储在共享首选项文件中的应用程序 问题是我想知道如何在 sharedpref 文件中添加新行(地图),但不编辑相同的地图或更新相同的地图键,值对

当我在添加新数据后检查它所在位置的 sharedpref 文件时,我发现同一地图正在更新,但没有添加新地图(或行)

MainActivity.kt

 //start sharedpreference to save data
    val sharedPrefFile = "goldinvesto"  //filename to save
    val collectdata:SharedPreferences = this.getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE)
    val editor:SharedPreferences.Editor=collectdata.edit()

         editor.putString("start_date",save_date)
         editor.putString("amount",save_amount_txt)
         editor.putString("currency",spin.selectedItem.toString())
         editor.putString("karat",spin2.selectedItem.toString())
         editor.putString("enter_price",save_enter_price)
         editor.apply()
         editor.commit()

sharedpref 文件位置:

您不能在 SharedPreferences 中执行此操作,因为它是基于具有 key/values.

的单个地图的文件

你必须使用数据库,SQLite、Room 等

要保存多张地图,您必须为其值提供唯一键,该键对于每张地图也必须是唯一的,例如:

editor.putString("start_date_1",save_date_1)
editor.putString("amount_1",save_amount_txt_1)
editor.putString("currency_1",spin.selectedItem_1.toString())
editor.putString("start_date_2",save_date_2)
editor.putString("amount_2",save_amount_txt_2)
editor.putString("currency_2",spin.selectedItem_2.toString())
editor.putString("start_date_3",save_date_3)
editor.putString("amount_3",save_amount_txt_3)
editor.putString("currency_3",spin.selectedItem_3.toString())

等等,但在共享首选项中存储大量数据是一种不好的做法,您应该使用 sqlite 或 room 或将数据存储在文件中