I have an activity which contains a listview, the activity (MainActivity
) launches another activity (HomeworkAddActivity
), this retrieves a string from the user and adds it to the listview (all of the above works).
However in order that the listview 'remembers' its contents whilest the other activity is launched I try to save the list to a file, code:
public void saveHomework() {
try {
@SuppressWarnings("resource")
FileOutputStream fos = new FileOutputStream(homeworkFileName);
fos = openFileOutput(homeworkFileName,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(homeworkItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void populateHomework() {
try {
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(homeworkFileName);
fis = getParent().openFileInput(homeworkFileName);
ObjectInputStream is = new ObjectInputStream(fis);
homeworkItems = (ArrayList<String>) is.readObject();
is.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I then read it from the file.
saveHomework
is called onPause
and populateHomework
:
@Override
public void onResume() {
super.onResume();
homeworkItems = new ArrayList<String>();
activity = this;
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
populateHomework();
homeworkListAdapter.notifyDataSetChanged();
}
However it only ever shows the items added by addHomeworkActivity
, not those 'saved' and 'restored' (they don't get saved/restored successfully), why is this?