首页 > 解决方案 > 使用文件路径保存 HashMap

问题描述

我有一个想要解决的简单数据问题。该程序会创建一个生成的按钮并要求您为其命名。然后它将该信息保存到 aHashMap类型<String, Fragment>并生成按钮。我创建了一个文件目录,以便它保存,HashMap所以当您退出并返回时,按钮仍然存在。我还没有弄清楚如何让它工作,现在它只保存一个按钮并丢弃其余按钮。任何帮助,将不胜感激!现在,我的一些文件内容被搞砸了,因为我正在测试一些东西,但似乎没有任何效果。

离开页面时如何保存HashMap到文件,HashMap返回页面时如何检索?

添加按钮的代码:

mLayout.addView(createNewTextView(newCataLine));

Fragment quotesFragment = QuotesFragment.newInstance();
cataFragmentMap.put(newCataLine, quotesFragment);

try {
    outputStream = getContext().openFileOutput(filename, Context.MODE_PRIVATE);
    ObjectOutputStream oout = new ObjectOutputStream(outputStream);
    oout.writeObject(cataFragmentMap);
    oout.close();

} catch (Exception ex) {
    Log.d("HELLO",ex.toString());
}

创建按钮的代码:

private TextView createNewTextView(String text) {
    final LinearLayout.LayoutParams lparams =
            new 
    LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
    LinearLayout.LayoutParams.WRAP_CONTENT);

    final Button cataButton = new Button(getContext());
    cataButton.setAllCaps(false);
    cataButton.setTextSize(40);
    cataButton.setLayoutParams(lparams);
    cataButton.setText(text);

    cataButton.setOnClickListener(cataButtonOnClick());

    return cataButton;
}

获取文件的代码:

File directory = getContext().getFilesDir();
    File file = new File(directory, filename);
    mLayout.addView(createNewTextView(*file*));

标签: javaandroidhashmap

解决方案


以下将允许您使用ObjectInputStream将其存储HashMap在文件中,然后使用检索它ObjectInputStream

try {
    File mapFile = new File(getDir("storage", MODE_PRIVATE), "hashmap");
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(mapFile));
    oos.writeObject(hashmap);
    oos.flush();
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(mapFile));
    HashMap map = (HashMap)ois.readObject();
} catch (Exception e) {
    // Handle exception here
}

推荐阅读