I have an application which contains a table to which you can add data, as seen in the images
And to create a second activity I have this code
public void metodo_anadir(View view) {
Intent intent = new Intent(getApplicationContext(), editarcontacto.class);
intent.putExtra("DATO",3);
startActivity(intent);
}
I put data in this second activity and then go back to the first
But when you give it back to add, to add another contact, the data is erased and the activity is recreated again. Why is this happening?
This is the complete code of the activity to edit data
package com.example.victor.miscompaneros;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneNumberUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class editarcontacto extends AppCompatActivity {
TextView campo1,campo2,campo3,campo4, campo5, campo6, campo7, campo8, advertencia1;
Integer telefono;
String nombre,papellido,sapellido,direccion,poblacion;
private static final int PICK_IMAGE = 100;
Uri imageUri;
ImageView foto_gallery;
Button boton1;
LocalDate fechanacimiento;
TableLayout lista;
TableRow tabla2,tabla3,tabla4,tabla5,tabla6,tabla7,tabla8,tabla9;
int filas=0, columnas=0;
ArrayList<Contacto> contactos= new ArrayList<Contacto>();
int i = 0;
@Override
@TargetApi(Build.VERSION_CODES.P)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editarcontacto);
//se asigna el campo de texto a la id que deseamos
campo1= (TextView) findViewById(R.id.campo1);
campo2= (TextView) findViewById(R.id.campo2);
campo3= (TextView) findViewById(R.id.campo3);
campo4= (TextView) findViewById(R.id.campo4);
campo5= (TextView) findViewById(R.id.campo5);
campo6= (TextView) findViewById(R.id.campo6);
campo7= (TextView) findViewById(R.id.campo7);
campo8= (TextView) findViewById(R.id.textView2);
foto_gallery = (ImageView)findViewById(R.id.imageView);
boton1= (Button) findViewById(R.id.button7);
lista= (TableLayout) findViewById(R.id.lista);
//definimos las tablas
tabla2= (TableRow) findViewById(R.id.tabla2);
/*tabla3= (TableRow) findViewById(R.id.tabla3);
tabla4= (TableRow) findViewById(R.id.tabla4);
tabla5= (TableRow) findViewById(R.id.tabla5);
tabla6= (TableRow) findViewById(R.id.tabla6);
tabla7= (TableRow) findViewById(R.id.tabla7);
tabla8= (TableRow) findViewById(R.id.tabla8);
tabla9= (TableRow) findViewById(R.id.tabla9);
*/
advertencia1= (TextView) findViewById(R.id.textView3);
foto_gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGallery();
}
});
Intent intent = getIntent();
//Le llega la accion que debe tomar
Bundle extras = intent.getExtras();
int dato= extras.getInt("DATO");
if (dato==1)
{
campo8.setText("AÑADIR CONTACTO");
boton1.setText("Añadir");
}
}
public void metodo_iniciar(View view) {
Intent intent = new Intent(getApplicationContext(), menucontactos.class);
intent.putExtra("DATO",1);
startActivity(intent);
finish();
}
@TargetApi(Build.VERSION_CODES.P)
public void metodo_editar2(View view) {
setContentView(R.layout.menucontactos);
TextView textview1=(TextView) findViewById(R.id.textView10);
TextView textview2=(TextView) findViewById(R.id.textView11);
TextView textview3=(TextView) findViewById(R.id.textView12);
TextView textview4=(TextView) findViewById(R.id.textView13);
//se añade el contacto
nombre=campo1.getText().toString();
papellido=campo2.getText().toString();
sapellido=campo3.getText().toString();
direccion=campo4.getText().toString();
poblacion=campo6.getText().toString();
try {
telefono=Integer.parseInt(campo5.getText().toString());
}
catch (Exception e){
advertencia1.setText("INTRODUZCA UN TELEFONO CORRECTO");
advertencia1.setVisibility(View.VISIBLE);
}try {
fechanacimiento = LocalDate.parse(campo7.getText().toString());
//convertimos la fecha tipo date en local date
//fechanacimiento = fechanacimiento.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate fechaactual = LocalDate.now();
LocalDate birthday = LocalDate.of(fechaactual.getYear(), fechanacimiento.getMonthValue(), fechanacimiento.getDayOfMonth());
if (fechaactual.isAfter(birthday))
birthday = birthday.plusYears(1);
Period diff = Period.between(fechaactual, birthday);
Contacto contacto = new Contacto(nombre, papellido, sapellido, direccion, poblacion, R.drawable.agenda, telefono, fechanacimiento);
contactos.add(contacto);
// se añade el array a la tabla del menu superior
do {
String n = contactos.get(i).getNombre();
String apellido1= contactos.get(i).getPapellido();
String apellido2= contactos.get(i).getSapellido();
String apellidos= apellido1 +" " + apellido2;
Integer telefono= contactos.get(i).getTelefono();
String poblacion= contactos.get(i).getPoblacion();
//LocalDate f = contactos.get(i).getFechanacimiento();
//añadimos los atributos a sus respectivo texto
textview1.setText(n);
textview2.setText(apellidos);
textview3.setText(String.valueOf(telefono));
textview4.setText(poblacion);
//convertimos fecha en string para poder añadirla al texto
//String fechatexto = contactos.get(i).convertirfecha(contactos.get(i).getFechanacimiento());
//textofecha.setText(fechatexto);
i++;
}while(i < (contactos.size()-1));
}
catch(Exception e){
Logger.getLogger(editarcontacto.class.getName()).log(Level.SEVERE, null, e);
//e.printStackTrace();
advertencia1.setText("INTRODUZCA UNA FECHA CORRECTA");
advertencia1.setVisibility(View.VISIBLE);
}
}
private void openGallery(){
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = data.getData();
foto_gallery.setImageURI(imageUri);
}
}
}
And the AndroidManifest XML (just in case)
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" android:screenOrientation="fullSensor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".menucontactos" android:screenOrientation="fullSensor"></activity>
<activity android:name=".editarcontacto" android:screenOrientation="fullSensor"></activity>
</application>