我有一个简单的数据问题需要解决。该程序创建一个生成的按钮并要求您为其命名。然后将该信息保存到 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*));
最佳答案
以下将允许您使用 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
}
关于java - 使用文件路径保存 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52168680/