使用文件路径保存HashMaps

时间:2018-09-04 14:35:03

标签: java android hashmap

我有一个要解决的简单数据问题。该程序将创建一个生成的按钮,并要求您为其命名。然后,该信息将保存到类型为HashMap的{​​{1}}并生成按钮。我创建了一个文件目录,以便保存<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;
}

1 个答案:

答案 0 :(得分:1)

以下内容将使您可以使用ObjectInputStreamHashMap存储在文件中,然后使用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
}
相关问题