晚上好!快问。
我正在尝试在我的应用中获得一个标签,以反映每次"保存"之后不断累加的一组int的总和。按下按钮。
此外,我想使用文件输入/输出来保存用户输入,以便它可以存储到文件中并在以后检索(但这是另一个问题)
我能够让标签反映一个与用户输入的最新int相等的数字,但我需要标签来反映用户输入的所有int的总和。
请看一看,我不确定为什么它没有做到它应该做的事情:
public View.OnClickListener onSave = new View.OnClickListener (){
@Override
public void onClick(View v) {
Info r = new Info();
EditText name = (EditText) findViewById(R.id.field_transaction);
EditText address = (EditText) findViewById(R.id.field_income_expense);
TextView total= (TextView)findViewById(R.id.total);
RadioGroup types = (RadioGroup) findViewById(R.id.rgrp_types);
switch (types.getCheckedRadioButtonId()) {
case R.id.rbtn_income:
r.setType("income");
break;
case R.id.rbtn_expense:
r.setType("expense");
break;
}
r.setName(transaction.getText().toString());
r.setAddress(income_expense.getText().toString());
r.setTotal(total.getText().toString());
String data = (income_expense.getText().toString()); //To get the value of income/expense and put it in a string
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes()); //To put string into FOS file
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Integer> storage = new ArrayList<>();
String collected = null;
FileInputStream fis = null;
int process = 0;
int sum = 0;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
int counter= 0;
while (fis.read(dataArray) != -1){ //Loops all code inside while there is still date inside file to read
collected = new String(dataArray); //Puts data into a string
process = Integer.parseInt( collected ); //Coverts that string itno an int.
storage.add(process); //Adds that int into an ArrayList
for(int i: storage){ //Adds all elements in the current state of the ArrayList together and makes puts it in int sum
sum += i;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
total.setText("Balance Total: " + sum + "Php"); //It is supposed to print the sum of all elements, but all it does is print the last input entered by user
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d("FoodTripActivity", "Name: " + r.getName() + "Address: " + r.getAddress() + "Type: " + r.getType());
adapter.add(r);
}
};