我正在保存并使用以下代码将ArrayList写入文件。这种方法只有在应用程序背景化时才能维持列表(onStop(),我猜),但是当我重新启动手机时,我的列表丢失了:
@SuppressWarnings("unchecked")
private ArrayList<HashMap<String, String>> loadListFromFile(
ArrayList<HashMap<String, String>> masterlistrev) {
try {
FileInputStream fis = openFileInput(serfilename);
ObjectInputStream ois = new ObjectInputStream(fis);
masterlistrev = (ArrayList<HashMap<String, String>>) ois
.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return masterlistrev;
}
private void writeListToFile(
ArrayList<HashMap<String, String>> masterlistrev, Context ctx,
String filename) {
FileOutputStream fos;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(masterlistrev);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
writeListToFile((ArrayList<HashMap<String, String>>) painItems,
getApplicationContext(), serfilename);
}
protected void onDestroy(){
writeListToFile((ArrayList<HashMap<String, String>>) painItems,
getApplicationContext(), serfilename);
super.onDestroy();
}
编辑 - 创建方法
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addscreen);
// getPainItems from the saved file
if (loadListFromFile((ArrayList<HashMap<String, String>>) painItems) != null)
painItems = loadListFromFile((ArrayList<HashMap<String, String>>) painItems);
// if it's the first time opening the app, then go to 'AddMyInfo.class'
serfilename = "hello";
SharedPreferences settings = this.getSharedPreferences("MyApp", 0);
SharedPreferences.Editor e = settings.edit();
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun) {
e.putBoolean("firstrun", false);
e.commit();
Intent intent = new Intent(this, AddMyInfo.class);
startActivity(intent);
}
// initialize painTitle and set its font
painTitle = (TextView) findViewById(R.id.painTitle);
Typeface font = Typeface.createFromAsset(getAssets(),
"Chantelli_Antiqua.ttf");
painTitle.setTypeface(font);
listthings = (ListView) findViewById(R.id.listthings);
from = new String[] { "row_1", "row_2" };
to = new int[] { R.id.row1, R.id.row2 };
adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout,
from, to);
listthings.setAdapter(adapter);
listthings.setOnItemClickListener(this);
listthings.setOnItemLongClickListener(this);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(this);
listthings.setChoiceMode(CHOICE_MODE_SINGLE);
}
正如您所看到的,我已经覆盖了OnStop()和OnDestroy方法来尝试这样做。我已将writeListToFile()放在OnCreate()方法中。任何解决方案都表示赞赏。
答案 0 :(得分:0)
嗯,是否有可能在重新启动时将您的空数组列表写入您的文件并随后尝试访问该列表?我觉得所有内容都正确地写入和读取但是有一个逻辑缺陷要么是破坏了你的文本文件(当你调用它时,MODE_PRIVATE会删除文件中的所有内容,而MODE_APPEND会写入它的末尾)或者写一个空白的arrayList。我能看到你的onCreate()方法吗?