【问题标题】:how to add a new map or row to sharedpreferences file如何将新地图或行添加到 sharedpreferences 文件
【发布时间】:2020-03-11 09:23:41
【问题描述】:

我正在构建一个应用程序来将数据存储在共享首选项文件中 问题是我想知道如何在 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 文件位置:

【问题讨论】:

  • 行/列保存数据,建议使用sqlite
  • 如果你想坚持 SharedPreference,每个地图都是一个单独的文件。

标签: android kotlin sharedpreferences


【解决方案1】:

您不能在 SharedPreferences 中执行此操作,因为它是基于具有键/值的单个映射的文件。

您必须使用数据库,包括 SQLite、Room 等。

【讨论】:

    【解决方案2】:

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

    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 或将数据存储在文件中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多