How can I keep a ListView with their data after returning from another activity?

1

I'm making a contact application for Android, I'm really new to this. I have a ListView in the MainActivity that should show the contacts or a message in case there are no contacts and a Floating Action Button, when pressed it takes me to another activity with a form to create the contact, when I return to the activity appears, but when you add another contact the first one disappears and that is the way I add a contact. How do I get the contact to be added to ListView of the main activity?

The code of my MainActivity:

public class MainActivity extends AppCompatActivity {

private ArrayList<Contacto> contactos = new ArrayList<>();
private ArrayList<String> nombresContactos = new ArrayList<>();
private ListView lstContactos;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    agregarFab();

    //Inicializa el campo de texto y la lista, pone en la interfaz el campo de texto cuando la lista está vacía:
    TextView tvVacio = (TextView) findViewById(R.id.tvVacio);
    lstContactos =  (ListView) findViewById(R.id.lstContactos);
    lstContactos.setEmptyView(tvVacio);

    //Agarra datos despues de crear un contacto nuevo y los devuelve para crear un contacto nuevo para la lista:
    try {

        Bundle contacto = getIntent().getExtras();
        String nombre = contacto.getString(getResources().getString(R.string.name));
        String telefono = contacto.getString(getResources().getString(R.string.phone));
        String email = contacto.getString(getResources().getString(R.string.email));
        String date = contacto.getString(getResources().getString(R.string.date));
        String descripcion = contacto.getString(getResources().getString(R.string.description));

        Contacto temp = new Contacto(nombre, date, descripcion, telefono, email);

        if (nombre != null && telefono != null) {
            contactos.add(temp);
            nombresContactos.add(temp.getNombre());
        }

        lstContactos.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nombresContactos));
    } catch (Exception e) {
        lstContactos.setEmptyView(tvVacio);
    }

}

public void agregarFab() {
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent nuevoContacto = new Intent(MainActivity.this, AgregarContacto.class);
            startActivity(nuevoContacto);
        }
    });
}

This is the code of the second activity to add the contact:

public class AgregarContacto extends AppCompatActivity {

private EditText etNombre;
private EditText etTelefono;
private EditText etEmail;
private EditText etDate;
private DatePickerDialog dpdFecha;
private EditText etDescription;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_agregar_contacto);

    //Inicializa UI:
    etNombre = (EditText) findViewById(R.id.etNombre);
    etTelefono = (EditText) findViewById(R.id.etTelefono);
    etEmail = (EditText) findViewById(R.id.etEmail);
    etDate = (EditText) findViewById(R.id.etDate);
    etDate.setInputType(InputType.TYPE_NULL);
    etDescription = (EditText) findViewById(R.id.etDescription);

    iniciarPicker();

    etDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                dpdFecha.show();
            }
        }
    });
}

public void iniciarPicker() {
    Calendar cal = Calendar.getInstance();
    dpdFecha = new DatePickerDialog(this, new OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            etDate.setText(String.valueOf(dayOfMonth) + "/" + String.valueOf(month) + "/" + String.valueOf(year));
        }
    }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH));
}

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_agregar_contacto_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.btnCancelar:
            Intent inicio = new Intent(this, MainActivity.class);
            startActivity(inicio);
            finish();
            break;
        case R.id.btnAceptar:
            Intent inicioSi = NavUtils.getParentActivityIntent(this);

            inicioSi.putExtra(getResources().getString(R.string.name), etNombre.getText().toString());
            inicioSi.putExtra(getResources().getString(R.string.phone), etTelefono.getText().toString());
            inicioSi.putExtra(getResources().getString(R.string.email), etEmail.getText().toString());
            inicioSi.putExtra(getResources().getString(R.string.date), etDate.getText().toString());
            inicioSi.putExtra(getResources().getString(R.string.description), etDescription.getText().toString());
            inicioSi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(inicioSi);
            finish();
            break;
    }
    return super.onOptionsItemSelected(item);
} }

If I add a first contact (A) it appears on the main screen:

But if I add another contact (B) I only get the latter:

So what I'm looking for is to make all the contacts I save appear on the list, not just the last one but I do not know how I can do it.

Thank you very much.

    
asked by Axel Pantoja 24.12.2016 в 07:43
source

1 answer

1

The error is that you add the values when you go from one Activity to another. So if in your MainActivity you have

Bundle contacto = getIntent().getExtras();
String nombre = contacto.getString(getResources().getString(R.string.name));
String telefono = contacto.getString(getResources().getString(R.string.phone));
String email = contacto.getString(getResources().getString(R.string.email));
String date = contacto.getString(getResources().getString(R.string.date));
String descripcion = contacto.getString(getResources().getString(R.string.description));

And you go to the Activity of adding contacts, write the corresponding data and add it do that:

Intent inicioSi = NavUtils.getParentActivityIntent(this);

inicioSi.putExtra(getResources().getString(R.string.name), etNombre.getText().toString());
inicioSi.putExtra(getResources().getString(R.string.phone), etTelefono.getText().toString());
inicioSi.putExtra(getResources().getString(R.string.email), etEmail.getText().toString());
inicioSi.putExtra(getResources().getString(R.string.date), etDate.getText().toString());
inicioSi.putExtra(getResources().getString(R.string.description), etDescription.getText().toString());
inicioSi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Replace the values you had previously saved. You will have to do the following:

Since you already have class Contacto and% ArrayList of type Contact created you must do this in MainActivity

public void agregarFab() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent nuevoContacto = new Intent(MainActivity.this, AgregarContacto.class);
            intent.putExtra("contactos", nombresContactos);
            startActivity(nuevoContacto);
        }
    });
}

As you see, I send the first Activity to the second your ArrayList<Contacto> called nombresContactos .

In the second Activity, you have to do:

ArrayList<Contacto> contactos = (ArrayList<Contacto>) getIntent().getSerializableExtra("contactos");

When you add a contact, do this:

case R.id.btnAceptar:
        String nombre = etNombre.getText().toString();
        String telefono = etTelefono.getText().toString();
        String email = etEmail.getText().toString();
        String date = etDate.getText().toString();
        String descripcion = etDescription.getText().toString();
        Contacto nuevo_contacto = new Contacto(nombre, date, descripcion, telefono, email);
        contactos.add(nuevo_contacto);
        Intent inicioSi = NavUtils.getParentActivityIntent(this);
        inicioSi.putExtra("contactos", contactos);
        startActivity(inicioSi);
        finish();
        break;

The new contact is added to an arraylist, then you send to your first Activity the array that now has a new item. Now it is only necessary to modify the first Activity and leave it like this:

ArrayList<Contacto> contactos = (ArrayList<Contacto>) getIntent().getSerializableExtra("contactos");
    
answered by 24.12.2016 / 12:54
source