【问题标题】:How can I add elements inside HashMap and save it? [Android]如何在 HashMap 中添加元素并保存? [安卓]
【发布时间】:2020-07-12 16:50:10
【问题描述】:

我是 HashMap 新手,如何在重新打开应用程序时永久保存并添加其他项目?

例如:

 private HashMap<String, Recognition> registered = new HashMap<>();
  public void register(String name, Recognition rec) {
  registered.put(name, rec);

}

我可以看到里面注册的所有项目:

for (Map.Entry<String, Recognition> entry : registered.entrySet()) {
    final String name = entry.getKey();
    ... }

但是当我关闭并重新打开应用程序时,我看不到保存在其中的所有已注册对象。 我看到很多人使用 SharedPreferences,但我不知道如何在预先保存的 hashmap 中添加项目。

【问题讨论】:

  • 数据结构(在本例中为哈希映射)只是一种以特定方式表示和利用数据来实现某事的方式,没有任何数据结构可以保存数据以外的数据应用程序的生命周期,这就是持久存储的用武之地

标签: android hashmap sharedpreferences


【解决方案1】:

您可以通过这种方式间接做到这一点:

//writing into file
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString( key, hashmap.getValue() );
editor.commit();

//reading from file
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
for( i = 0;i < size;i++) )
   pref.getString( i , defaultValue );

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2013-07-18
    相关资源
    最近更新 更多