I am developing an app, in which the user puts some numeric info in some text fields, the app is supposed to write the info into a txt file for later use, for example next time the app is opened or a refresh button is pressed the numbers should be read from the file and loaded into the same text fields so the user can change them if needed. While both "writer" and "loader" functions seem to be working, the problem is that every time "loader" is being called, it loads the data from some previously saved file and not the file that is created right now by the "writer". If the user wants the new saved data to be loaded into text fields, he needs to close and reopen the app again. To explain the situation better, I placed some scenario after the codes. Any ideas what is wrong and what can be done?
Here is the code that I'm using to put the info into the file, and it works fine:
public void writer(View view){
try {
FileOutputStream fos = openFileOutput("myfilename", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
PrintStream prntst = new PrintStream(fos);
txtEditor=(EditText)findViewById(R.id.editText1);
prntst.println (txtEditor.getText().toString());
txtEditor=(EditText)findViewById(R.id.EditText02);
prntst.println (txtEditor.getText().toString());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is the code I'm using to read the info from file to some ArrayList, then this ArrayList is used to fill up the textfields, this is also working fine (fine means without error):
public void reader(View view){
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("myfilename")));
Scanner scanner = new Scanner(inputReader);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
bld.add(line);
}
inputReader.close();
scanner.close();
txtEditor=(EditText)findViewById(R.id.editText1);
txtEditor.setText(bld.get(0));
txtEditor=(EditText)findViewById(R.id.EditText02);
txtEditor.setText(bld.get(1));
} catch (IOException e) {
e.printStackTrace();
txtEditor=(EditText)findViewById(R.id.editText1);
bld.add((txtEditor.getText().toString()));
txtEditor=(EditText)findViewById(R.id.EditText02);
bld.add((txtEditor.getText().toString()));
}
}
Scenario:
PS. the variable bld is global and defined in the MainActivity:
ArrayList<String> bld = new ArrayList<String>();
Thank you,
The problem may be with the global ArrayList variable 'bld'. It's OK to define it globally, But initialize it locally.
The problem is that, you are calling as bld.get(0)
, But the new values are appended after it.
Add the line bld = new ArrayList<String>();
inside your 'reader' function.