I want to show the sum of all prices (e.g. £18.99 £50 etc.) from a file in a TextView, currently it just reads/shows the last price from the file.
This is my current code for writing to a file:
total.setText(total.getText());
try {
FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE);
fos.write(total.getText().toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
This is my current code for reading from a file (member burmat suggested some changes):
public void savingstotalbutton(View view) {
double total = 0;
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("TotalSavings")));
String inputString;
@SuppressWarnings("unused")
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
if (inputString.length() > 0) {
String line = inputString.replaceAll("[^0-9.]", "");
total = total + Double.parseDouble(line);
}
}
savingstotaltext.setText(String.valueOf(total));
} catch (IOException e) {
e.printStackTrace();
}
}
Any help is appreciated.
Edit:
I modified the contents of the TotalSavings.txt manually and added different prices and copied that to the /files folder of the App. It reads all the prices and gives the sum which works but the problem is that the write function overwrites the 1st line, it never goes to the next line.
Edit 2: The whole code which uses calc button to show calculation and the write the result to the file TotalSavings.txt
public void calc(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
if (price.getText().toString().equals(""))
return;
if (disc.getText().toString().equals(""))
return;
double priceVal = Double.parseDouble(price.getText().toString());
double discVal = Double.parseDouble(disc.getText().toString());
double discount = priceVal / 100.0 * discVal;
int di = (int) (discount * 100);
double totalVal = priceVal - (di / 100.0);
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.getDefault());
savings.setText(nf.format(discount));
total.setText(nf.format(totalVal));
savings.setText(savings.getText());
try {
FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE);
fos.write(savings.getText().toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…