java - 使用文件路径保存 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*));
解决方案
以下将允许您使用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
}
推荐阅读
- javascript - 在函数中返回订单对象
- lua - 谁能帮我理解lua中的这行代码
- android - Kotlin 中的音乐 URI 空指针异常
- phabricator - 如何使用 Phabricator “maniphest.edit” API 向列添加票证,同时还使用其“beforePHIDs”参数?
- javascript - 我的模块化 JS 代码有问题 TypeError 不是函数
- javascript - 动画后 CSS 和 JavaScript 不居中
- c++ - 在 C++ 中从数组中删除重复项
- laravel - 根据数据库中的计数填充下拉列表
- sql - 在 postgresql 中创建触发器时在“AS”处或附近出现语法错误
- javascript - beforeunload 事件未在 IOS 设备中触发