So the Title pretty much sums up my problem, but I’m not sure what I’m doing wrong as far as code goes.
Here’s the snipbit where I write to the file:
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(assignmentTitle + "\n" + assignmentDate + "\n");
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
//catch errors opening file
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Edit: This is where I read from the file every time the activity is called
private void readDataFromFile() {
try {
//Opens a file based on the file name stored in FILENAME.
FileInputStream myIn = openFileInput(FILENAME);
//Initializes readers to read the file.
InputStreamReader inputReader = new InputStreamReader(myIn);
BufferedReader BR = new BufferedReader(inputReader);
//Holds a line from the text file.
String line;
//currentAssignment to add to the list
Assignment currentAssignment = new Assignment();
while ((line = BR.readLine()) != null) {
switch (index) {
case 0:
//Toast.makeText(this, line, Toast.LENGTH_LONG).show();
currentAssignment.setTitle(line);
index++;
break;
case 1:
//Toast.makeText(this, Integer.toString(assignmentListIndex), Toast.LENGTH_LONG).show();
currentAssignment.setDate_due(line);
Statics.assignmentList.add(assignmentListIndex, currentAssignment);
index = 0;
assignmentListIndex++;
currentAssignment = new Assignment();
break;
default:
Toast.makeText(this, "error has occured", Toast.LENGTH_SHORT).show();
break;
}
}
BR.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thats in a function when the user clicks on create a new assignment. When they click the save button on the assignment, it’s supposed to save that assignment to a file and then I read it later and display it in a listView. What it’s doing is displaying the first item in the listView and when I create a new assignment, it’s overwriting the previous text in save file and replacing it in the listView. If you guys need me to post more code Let me know. I’m so confused as to why this isn’t working 🙁
Instead of
Context.MODE_PRIVATE, useContext.MODE_APPEND. This mode appends to an existing file instead of erasing it. (More detail on those in theopenFileOutputdocs.)