如何在 HashMap 中添加元素并保存? [Android]

How can I add elements inside HashMap and save it? [Android]

我是 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 中添加项目。

您可以通过这种方式间接完成:

//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 );