Reputation: 108
if I click a button a file will be created and an integer value gets written in the file. If I click another button the value gets extracted out of the file. If I close the app an restart it the file can't be found. Is it because the file is created in de android:onCLick method?
here are the two methods:
Write:
public void buttonAddClick (View view){
file = new File(directory, "file" + c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH) + ".txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file,true));
bufferedWriter.append(editAm.getText());
bufferedWriter.append("\n");
bufferedWriter.close();
editAm.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
}
Read:
public void buttonShowClick(View view) {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
zwischensumme = 0;
String line;
while ((line = bufferedReader.readLine()) != null) {
zwischensumme += Double.parseDouble(line);
line = "";
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (NumberFormatException e){
e.printStackTrace();
file.delete();
}
}
Upvotes: 0
Views: 155
Reputation: 955
Looks like you might get a NumberFormatException
.
Check stacktrace to see if you get into the catch (NumberFormatException e)
block.
If you fall into this block, then the file is indeed deleted due to your catch block :
catch (NumberFormatException e){
e.printStackTrace();
file.delete();
}
Also Hermann Klecker is right. You name your file based on date time.
You don't show how you retrieve the file in the read part. Is it based on a file name ?
As you may not know the file name (due to date/time relation) do something like so in onResume if (file == null)
:
File directory = new File("/path/to/directory");
File[] foundFiles = directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("file");
}
});
if (!foundFiles.isEmpty()) {
file = foundFiles[0];
}
This way, if the first file name start with 'file', it will be used
Upvotes: 1
Reputation: 14068
You may get confused with your file variable. It seems to be an instance variable of your class. It is being insantiated in buttonAddClick. When you now run your app again, it is not being instaniated but used in buttonShowClick (as far as we can see).
I guess it is null.
Upvotes: 0