【问题标题】:Android Shared Preferences prevent overwriting while storing objectAndroid Shared Preferences 防止在存储对象时覆盖
【发布时间】:2019-08-11 18:56:53
【问题描述】:

我正在使用共享首选项将字符串存储到日历日。我有一个类,它添加一个装饰器并将一个字符串保存到选定的日期(来自用户输入的字符串),它工作正常。当我尝试添加新日期时出现问题,共享首选项被覆盖(这是预期的)。

将字符串保存到日历日的方法

        final CalendarDay day1 = date;
                final ArrayList<CalendarDay> selectedEventDay = new ArrayList<>();
                for (int i = 0; i < 30; i++) {
                    selectedEventDay.add(day1);
            }
             String editedText = noteEditText.getText().toString();
                            CustomEventDay customEventDay = new CustomEventDay(editedText, selectedEventDay);
                            SharedPreferences.Editor prefsEditor = mPrefs.edit();
                            Gson gson = new Gson();
                            String json = gson.toJson(customEventDay);
                            prefsEditor.putString("CustomEventCal", json);
                            prefsEditor.apply();

我想知道是否有办法使用相同的方法为新日期保存新数据。目前,如果用户选择另一个日期,则存储在共享首选项中的当前日期及其字符串和相关日期将被新的日期数据覆盖。

【问题讨论】:

  • 您需要为每一天指定唯一的偏好键,但不鼓励这样做。对于任何复杂的数据,您应该考虑建立某种数据库。
  • 您可以使用不同的键添加更多日期。对于少量的日期,这种方法是可以的,但如果你想用于大量的数据,最好使用sqlite数据库。 Sqlite 将提供一种更方便的方式来存储和检索数据。
  • 好的,我将研究将数据存储在 SQLite 中。我假设也可以使用我在这里使用的相同 gson.Json 方法存储在 SQLite 中?
  • 是的,您可以将 Gson 与 sqlite 一起使用。

标签: java android arrays sharedpreferences androidx


【解决方案1】:

即使在使用 SQlite 的 cmets 中推荐的方式很好,有时您只需要少量数据,然后使用 Shared Preferences 会更容易:

因此,如果事件的数量仍然很少,您可以开始使用对象数组,然后再次使用 Gson:

Gson gson = new Gson();
List<CustomEventDay> events = // initialized with the content of your shared preferences
events.add(customEventDay);
String json = gson.toJson(events);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2017-05-09
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多