I have three Activitys, the main one:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] archivos = fileList();
if (!existe(archivos, "notas.txt")) {
crear();
}
}
public void calcular(View v){
Intent i = new Intent(this, Calcular.class);
startActivity(i);
}
public void ver(View v){
Intent i = new Intent(this, Ver.class);
startActivity(i);
}
private boolean existe(String[] archivos, String archbusca) {
for (int f = 0; f < archivos.length; f++)
if (archbusca.equals(archivos[f]))
return true;
return false;
}
private void crear(){
try {
OutputStreamWriter archivo = new OutputStreamWriter(openFileOutput(
"notas.txt", AppCompatActivity.MODE_PRIVATE));
}catch(IOException e){}
}
}
One that writes the results of an operation in a '.txt':
public class Calcular extends AppCompatActivity {
private EditText et1, et2;
private RadioButton rb1, rb2, rb3, rb4;
private int r=3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calcular);
et1 = findViewById(R.id.et1);
et2 = findViewById(R.id.et2);
rb1 = findViewById(R.id.rb1);
rb2 = findViewById(R.id.rb2);
rb3 = findViewById(R.id.rb3);
rb4 = findViewById(R.id.rb4);
}
public void operar(View v){
int a, b;
a = Integer.parseInt(et1.getText().toString());
b = Integer.parseInt(et2.getText().toString());
if(rb1.isChecked()){
r = a + b;
}
else if(rb2.isChecked()){
r = a - b;
}
else if(rb3.isChecked()){
r = a * b;
}
else if(rb4.isChecked()){
r = a / b;
}
try {
FileWriter archivo = new FileWriter(getFileStreamPath("notas.txt"), true);
archivo.write( String.valueOf(r) );
archivo.flush();
archivo.close();
} catch (IOException e) {
}
}
public void volver(View v){
finish();
}
}
And the other should read and print the results that are accumulating:
public class Ver extends AppCompatActivity {
private TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver);
tv1 = findViewById(R.id.tv1);
try{
InputStreamReader archivo = new InputStreamReader(
openFileInput("notas.txt"));
BufferedReader br = new BufferedReader(archivo);
String linea = br.readLine().toString();
String todo = "";
while(linea != null){
todo = todo + linea;
linea = br.readLine().toString();
}
br.close();
archivo.close();
tv1.setText(todo);
}catch(IOException e){}
}
public void volver(View v) {
finish();
}
}
But only write the last result. How can I solve that? Thanks.
Could it be that the write () method is overwriting the values that were stored?