After several weeks of non-programming, I decided to end my application. Last time I could not write and read, but now I want to do it. I could use databases, but that seems a lot easier. I found this page where I copied the code. At least now I can check the contents of the file on my phone (as long as I do not use virtual SD cards, but this will definitely speed up testing). The problem with this code is that every time I write a file, close the application, and then open it again and write the file again, the contents of the file are reset.
File root = Environment.getExternalStorageDirectory(); File file = new File(root, "tomato50.txt"); if (assignArr.size() > 0) { try { if (root.canWrite()) { FileWriter filewriter = new FileWriter(file); BufferedWriter out = new BufferedWriter(filewriter); for (int i = 0; i < assignArr.size(); i++) { out.write(assignArr.get(i) + "\n"); Toast.makeText(MainActivity.this, "out: " + assignArr.get(i), Toast.LENGTH_LONG) .show(); } out.close(); } } catch (IOException e) { Log.e("TAG", "Could not write file " + e.getMessage()); } }
eg.
- I put one element in assignArr.
- The item is written to the file.
- I am closing the application. AssignArr becomes empty because it is a variable.
- I open the application.
- I put an element in assignArr.
- I am closing the application. AssignArr becomes empty because it is a variable.
- I open a file that shows only the last item.
source share