Caught in the try catch [duplicate]

1

Pressing a button on my program is always caught in catch

The error that I get when executing the program is as follows

E/editarcontacto: null
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
    at com.example.victor.miscompaneros.editarcontacto.metodo_editar2(editarcontacto.java:138)
    at java.lang.reflect.Method.invoke(Native Method)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

The error jumps me in the line:

contacto.contactos.add(contacto);

editcontact.java

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;

    @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) {

        //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());


            //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);

            contacto.contactos.add(contacto);

            // se añade el array a la tabla del menu superior


            for (int i = 0; i < contacto.contactos.size(); i++) {


                String n = contacto.contactos.get(i).getNombre();
                LocalDate f = contacto.contactos.get(i).getFechanacimiento();

                //metemos el nombre y el cumpleaños en sus determinadas columnas
                TextView textonombre = new TextView(this);
                TextView textofecha = new TextView(this);
                for (i = 0; i < contacto.contactos.size(); i++)
                    textonombre.setText(contacto.contactos.get(i).getNombre());

                //convertimos fecha en string para poder añadirla al texto
                String fechatexto = contacto.contactos.get(i).convertirfecha(contacto.contactos.get(i).getFechanacimiento());

                textofecha.setText(fechatexto);

                //añadimos los atributos a sus respectivas columnas
                tabla2.addView(textonombre);
                tabla2.addView(textofecha);

            }
        }
        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);
        }
    }
}

XML file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"
    tools:layout_editor_absoluteY="25dp">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="37dp"
        android:text="EDITAR CONTACTO"
        android:textColor="@android:color/white"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/Nombre"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="7dp"
        android:layout_marginEnd="25dp"
        android:layout_marginRight="25dp"
        android:text="Nombre"
        android:textColor="@android:color/white"
        app:layout_constraintEnd_toStartOf="@+id/campo1"
        app:layout_constraintTop_toTopOf="@+id/campo1" />

    <TextView
        android:id="@+id/apellido1"
        android:layout_width="0dp"
        android:layout_height="23dp"
        android:layout_marginTop="11dp"
        android:layout_marginBottom="11dp"
        android:text="Apellido 1"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toTopOf="@+id/campo3"
        app:layout_constraintEnd_toEndOf="@+id/apellido2"
        app:layout_constraintStart_toStartOf="@+id/apellido2"
        app:layout_constraintTop_toTopOf="@+id/campo2" />

    <TextView
        android:id="@+id/Telefono"
        android:layout_width="0dp"
        android:layout_height="22dp"
        android:layout_marginStart="28dp"
        android:layout_marginLeft="28dp"
        android:layout_marginEnd="25dp"
        android:layout_marginRight="25dp"
        android:text="Teléfono"
        android:textColor="@android:color/white"
        app:layout_constraintBaseline_toBaselineOf="@+id/campo5"
        app:layout_constraintEnd_toStartOf="@+id/campo5"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/apellido2"
        android:layout_width="0dp"
        android:layout_height="18dp"
        android:layout_marginStart="6dp"
        android:layout_marginLeft="6dp"
        android:layout_marginTop="79dp"
        android:layout_marginEnd="7dp"
        android:layout_marginRight="7dp"
        android:layout_marginBottom="79dp"
        android:text="Apellido 2"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toTopOf="@+id/Fecha"
        app:layout_constraintEnd_toStartOf="@+id/campo1"
        app:layout_constraintStart_toStartOf="@+id/Telefono"
        app:layout_constraintTop_toTopOf="@+id/Nombre" />

    <TextView
        android:id="@+id/Fecha"
        android:layout_width="wrap_content"
        android:layout_height="17dp"
        android:layout_marginStart="18dp"
        android:layout_marginLeft="18dp"
        android:layout_marginEnd="38dp"
        android:layout_marginRight="38dp"
        android:text="F.nacimiento"
        android:textColor="@android:color/white"
        app:layout_constraintBaseline_toBaselineOf="@+id/campo7"
        app:layout_constraintEnd_toStartOf="@+id/campo7"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/Direccion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="15dp"
        android:layout_marginEnd="38dp"
        android:layout_marginRight="38dp"
        android:text="Dirección"
        android:textColor="@android:color/white"
        app:layout_constraintEnd_toStartOf="@+id/campo4"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/campo3" />

    <TextView
        android:id="@+id/foto"
        android:layout_width="59dp"
        android:layout_height="26dp"
        android:layout_marginStart="43dp"
        android:layout_marginLeft="43dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="44dp"
        android:layout_marginRight="44dp"
        android:layout_marginBottom="66dp"
        android:text="FOTO"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="@+id/campo6"
        app:layout_constraintEnd_toEndOf="@+id/campo4"
        app:layout_constraintStart_toEndOf="@+id/campo6"
        app:layout_constraintTop_toBottomOf="@+id/campo4" />

    <TextView
        android:id="@+id/Poblacion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_marginStart="28dp"
        android:layout_marginLeft="28dp"
        android:text="Población"
        android:textColor="@android:color/white"
        app:layout_constraintBaseline_toBaselineOf="@+id/campo6"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="48dp"
        android:layout_marginLeft="48dp"
        android:layout_marginBottom="36dp"
        android:onClick="metodo_editar2"
        android:text="Editar"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="53dp"
        android:layout_marginRight="53dp"
        android:layout_marginBottom="37dp"
        android:onClick="metodo_iniciar"
        android:text="Volver"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <EditText
        android:id="@+id/campo1"
        android:layout_width="124dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="23dp"
        android:hint="Introduce tu nombre aquí"
        android:textColorHint="@android:color/background_light"
        android:textSize="10dp"
        app:layout_constraintStart_toStartOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <EditText
        android:id="@+id/campo2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="9dp"
        android:layout_marginBottom="9dp"
        android:hint="Introduce 1apellido aquí"
        android:textColorHint="@android:color/background_light"
        android:textSize="10dp"
        app:layout_constraintBottom_toTopOf="@+id/apellido2"
        app:layout_constraintEnd_toEndOf="@+id/campo3"
        app:layout_constraintStart_toStartOf="@+id/campo3"
        app:layout_constraintTop_toBottomOf="@+id/campo1" />

    <EditText
        android:id="@+id/campo3"
        android:layout_width="179dp"
        android:layout_height="33dp"
        android:layout_marginStart="78dp"
        android:layout_marginLeft="78dp"
        android:layout_marginEnd="79dp"
        android:layout_marginRight="79dp"
        android:hint="Introduce 2apellido aquí"
        android:textColorHint="@android:color/background_light"
        android:textSize="10dp"
        app:layout_constraintBottom_toBottomOf="@+id/apellido2"
        app:layout_constraintEnd_toEndOf="@+id/campo4"
        app:layout_constraintStart_toStartOf="@+id/Direccion"
        app:layout_constraintTop_toBottomOf="@+id/apellido2" />

    <EditText
        android:id="@+id/campo4"
        android:layout_width="0dp"
        android:layout_height="31dp"
        android:layout_marginTop="80dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="80dp"
        android:hint="Introduce direccion aquí"
        android:textColorHint="@android:color/background_light"
        android:textSize="10dp"
        app:layout_constraintBottom_toTopOf="@+id/Telefono"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/Direccion"
        app:layout_constraintTop_toTopOf="@+id/apellido1" />

    <EditText
        android:id="@+id/campo5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="36dp"
        android:layout_marginRight="36dp"
        android:digits="0123456789+"
        android:hint="Introduce telefono aquí"
        android:inputType="phone"
        android:textColorHint="@android:color/background_light"
        android:textSize="10dp"
        app:layout_constraintEnd_toStartOf="@+id/imageView"
        app:layout_constraintStart_toEndOf="@+id/Telefono"
        app:layout_constraintTop_toBottomOf="@+id/campo7" />

    <EditText
        android:id="@+id/campo6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="14dp"
        android:hint="Introduce población aquí"
        android:textColorHint="@android:color/background_light"
        android:textSize="10dp"
        app:layout_constraintStart_toStartOf="@+id/campo5"
        app:layout_constraintTop_toBottomOf="@+id/campo5" />

    <EditText
        android:id="@+id/campo7"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="6dp"
        android:layout_marginRight="6dp"
        android:layout_marginBottom="268dp"
        android:hint="Introduce tu fecha de nacimiento aquí(yyyy-mm-dd)"
        android:inputType="date"
        android:textColorHint="@android:color/background_light"
        android:textSize="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/Fecha"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="26dp"
        android:layout_marginEnd="52dp"
        android:layout_marginRight="52dp"
        android:layout_marginBottom="25dp"
        app:layout_constraintBottom_toTopOf="@+id/button7"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/campo5"
        app:layout_constraintTop_toBottomOf="@+id/campo7"
        app:srcCompat="@drawable/foto" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="88dp"
        android:layout_marginLeft="88dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="234dp"
        android:text="INTRODUCE UN NUMERO CORRECTO"
        android:visibility="invisible"
        android:textColor="@android:color/holo_red_dark"
        app:layout_constraintBottom_toTopOf="@+id/campo7"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

**Contacto.java**

    public class Contacto {

    String nombre, papellido,sapellido,direccion,poblacion;
    Integer telefono, foto;
    LocalDate fechanacimiento;
    ArrayList<Contacto> contactos;

    public Contacto(String nombre, String papellido, String sapellido, String direccion, String poblacion, int foto, Integer telefono, LocalDate fechanacimiento) {
        this.nombre = nombre;
        this.papellido = papellido;
        this.sapellido = sapellido;
        this.direccion = direccion;
        this.poblacion = poblacion;
        this.foto = foto;
        this.telefono = telefono;
        this.fechanacimiento = fechanacimiento;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getPapellido() {
        return papellido;
    }

    public void setPapellido(String papellido) {
        this.papellido = papellido;
    }

    public String getSapellido() {
        return sapellido;
    }

    public void setSapellido(String sapellido) {
        this.sapellido = sapellido;
    }

    public String getDireccion() {
        return direccion;
    }

    public void setDireccion(String direccion) {
        this.direccion = direccion;
    }

    public String getPoblacion() {
        return poblacion;
    }

    public void setPoblacion(String poblacion) {
        this.poblacion = poblacion;
    }

    public Integer getFoto() {
        return foto;
    }

    public void setFoto(Integer foto) {
        this.foto = foto;
    }

    public Integer getTelefono() {
        return telefono;
    }

    public void setTelefono(Integer telefono) {
        this.telefono = telefono;
    }

    public LocalDate getFechanacimiento() {
        return fechanacimiento;
    }

    public void setFechanacimiento(LocalDate fechanacimiento) {
        this.fechanacimiento = fechanacimiento;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)

    public String convertirfecha(LocalDate fechanacimiento){

        //convertimos fecha(LocalDate) en Date
        Date date1 = Date.from(fechanacimiento.atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println("java.time.LocalDate -> java.util.Date: " + date1);

        //convertimos date en String

        String sDate2 = fechanacimiento.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
        System.out.println("java.time.LocalDate -> String: " + sDate2);

        //devolvemos string
        return(sDate2);
    }

}
    
asked by victor96 14.11.2018 в 13:36
source

2 answers

1

The error that you say is due to the fact that you have not initialized the ArrayList of the Contact class, you must put the constructor in the following way:

public Contacto(String nombre, String papellido, String sapellido, String direccion, String poblacion, int foto, Integer telefono, LocalDate fechanacimiento) {
    this.nombre = nombre;
    this.papellido = papellido;
    this.sapellido = sapellido;
    this.direccion = direccion;
    this.poblacion = poblacion;
    this.foto = foto;
    this.telefono = telefono;
    this.fechanacimiento = fechanacimiento;
    contactos = new ArrayList<>();
}
    
answered by 14.11.2018 / 15:03
source
0

The problem is when you execute the add method of the Contacts ArrayList, when you instantiate the Contact object, you do not automatically instantiate the list, that is, even if you say New Contact, the list will be in null and therefore you will get an error when you want use one of their methods.

You can do encapsulation (get () and set ()) to the ArrayList and initialize it with setContacts (new ArrayList) and in this way you will be able to use the add method.

Remember that every time you start the list all the data that you have stored there will be erased, therefore it is advisable to initialize the list only once in the whole process.

    
answered by 14.11.2018 в 15:09