java - 使用文件路径保存 HashMap

标签 java android hashmap

我有一个简单的数据问题需要解决。该程序创建一个生成的按钮并要求您为其命名。然后将该信息保存到 HashMap类型 <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*));

最佳答案

以下将允许您使用 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
}

关于java - 使用文件路径保存 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52168680/

相关文章:

java - 打印一副牌,然后洗牌并重新打印

java - 如何制作对话框 "You are using 3G. Connect to WiFi"?

android - 使用 jni 库构建 AOSP 应用程序

c++ - 我如何重载模板类的下标运算符

java - 如何从java中的hashmap中删除字符串数组值?

java - 无法使用我知道 HTML 是使用 CSS 选择器构建的所有元素定位器来定位元素

java - 通过其连接的适配器调用 Activity 的方法对应用程序的面向对象设计有何影响?

android - 为 NFC Intent 声明自定义 mimeType

android - Android键盘上的鼠标拖动器

string - Groovy 字符串到 HashMap 转换