1

I'm having an issue with saving the instance of an ArrayList of custom objects in an Activity and then retreiving it after doing some stuff in another Activity. Inside the first Activity (which has the ArrayList), there is a button to start a second activity. Inside this second Activity the user is asked to create a new object that will be added afterwards in the ArrayList of the first Activity, so that when the second Activity finishes the first Activity is shown again with a ListView of all the objects (including the last one created). The problem I'm facing is that only the last object created is being shown in the ListView.

Here is the code of the first Activity:

public class CargasMin extends AppCompatActivity implements View.OnClickListener {

RelativeLayout rl_CargasMin;

ImageButton bt_AdDep;
Button bt_CalcCargas;

ListView listView_Dep;

ArrayList<Dependencia> listaDeDependencias = new ArrayList<Dependencia>();

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

    rl_CargasMin = (RelativeLayout) findViewById(R.id.cargasMinLayout);

    bt_AdDep = (ImageButton) findViewById(R.id.bt_AdDep_CargasMin);
    bt_CalcCargas = (Button) findViewById(R.id.bt_CalcCargas_CargasMin);
    bt_AdDep.setOnClickListener(this);
    bt_CalcCargas.setOnClickListener(this);

    // This seems not to be working!
    if(savedInstanceState == null) { }
    else {
        listaDeDependencias = savedInstanceState.getParcelableArrayList("key");
    }

    // Get last object created
    Intent intent_de_AdDep = getIntent();
    Dependencia dependenciaAAdicionar = (Dependencia) intent_de_AdDep.getParcelableExtra("novaDependencia");
    if(dependenciaAAdicionar == null) { }
    else {
        listaDeDependencias.add(dependenciaAAdicionar);
    }

    //Cria Adapter pra mostrar dependencias na ListView
    DependenciaAdapter adapterDeDependencias = new DependenciaAdapter(this, R.layout.adapter_dependencia, listaDeDependencias);

    //Seta Adapter
    listView_Dep = (ListView) findViewById(R.id.listView_Dep_CargasMin);
    listView_Dep.setAdapter(adapterDeDependencias);
}


@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.bt_AdDep_CargasMin:
            Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
            startActivity(intent_AdDep);
            break;
        case R.id.bt_CalcCargas_CargasMin:
            //
            break;
    }
}


@Override
protected void onSaveInstanceState(Bundle outState) {
    // Aqui se salva a listaDeDependencias quando a Atividade eh momentaneamente fechada.
    outState.putParcelableArrayList("key", listaDeDependencias);
    super.onSaveInstanceState(outState);
    }
}

This is the code of my custom class Dependencia:

public class Dependencia implements Parcelable {
String nome;
int tipo;

float largura = 0;
float comprimento = 0;
float area = 0;
float perimetro = 0;

// Constructor da classe Dependencia.
public Dependencia(String nomeDep, int tipoDep) {
    nome = nomeDep;
    tipo = tipoDep;
}

private Dependencia(Parcel in) {
    nome = in.readString();
    tipo = in.readInt();
    largura = in.readFloat();
    comprimento = in.readFloat();
    area = in.readFloat();
    perimetro = in.readFloat();
}

public int describeContents() {
    return 0;
}

public void writeToParcel(Parcel out, int flags) {
    out.writeString(nome);
    out.writeInt(tipo);
    out.writeFloat(largura);
    out.writeFloat(comprimento);
    out.writeFloat(area);
    out.writeFloat(perimetro);
}

public static final Parcelable.Creator<Dependencia> CREATOR = new Parcelable.Creator<Dependencia>() {
    public Dependencia createFromParcel(Parcel in) {
        return new Dependencia(in);
    }

    public Dependencia[] newArray(int size) {
        return new Dependencia[size];
    }
};
}

And this is the code of the second Activity:

public class AdDep extends AppCompatActivity implements View.OnClickListener {

RelativeLayout rl_AdDep;

EditText et_Nome;
EditText et_Largura;
EditText et_Comprimento;
EditText et_Area;
EditText et_Perimetro;

Spinner spinner_Tipo;
String vetorTipo[];
int tipoEscolhido;

Button bt_AdDep1;
Button bt_AdDep2;

Dependencia novaDependencia;

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

    rl_AdDep = (RelativeLayout)findViewById(R.id.adDepLayout);

    et_Nome = (EditText) findViewById(R.id.et_Nome_AdDep);
    et_Largura = (EditText) findViewById(R.id.et_Largura_AdDep);
    et_Comprimento = (EditText) findViewById(R.id.et_Comprimento_AdDep);
    et_Area = (EditText) findViewById(R.id.et_Area_AdDep);
    et_Perimetro = (EditText) findViewById(R.id.et_Perimetro_AdDep);

    spinner_Tipo = (Spinner) findViewById(R.id.spinner_Tipo_AdDep);

    bt_AdDep1 = (Button) findViewById(R.id.bt_AdDep1);
    bt_AdDep2 = (Button) findViewById(R.id.bt_AdDep2);


    // Adicionando opcoes no spinner
    vetorTipo = new String[5];
    vetorTipo[0] = "Banheiro";
    vetorTipo[1] = "Varanda";
    vetorTipo[2] = "Cozinha/Copa/Serviço/etc.";
    vetorTipo[3] = "Sala/Dormitório";
    vetorTipo[4] = "Outro";

    // Criando ArrayAdapter de strings pro spinner
    ArrayAdapter<String> adapterTipo = new ArrayAdapter<String>(AdDep.this, android.R.layout.simple_spinner_item, vetorTipo);

    // Setando o Adapter
    spinner_Tipo.setAdapter(adapterTipo);

    // Valor default do spinner (hint)
    spinner_Tipo.setSelection(0);


    bt_AdDep1.setOnClickListener(this);
    bt_AdDep2.setOnClickListener(this);
}


@Override
public void onClick(View v) {
    if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Banheiro"))
        tipoEscolhido = 1;
    else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Varanda"))
        tipoEscolhido = 2;
    else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Cozinha/Copa/Serviço/etc."))
        tipoEscolhido = 3;
    else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Sala/Dormitório"))
        tipoEscolhido = 4;
    else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Outro"))
        tipoEscolhido = 5;

    novaDependencia = new Dependencia(et_Nome.getText().toString(), tipoEscolhido);

    switch(v.getId()) {
        case R.id.bt_AdDep1:
            novaDependencia.largura = Float.valueOf(et_Largura.getText().toString());
            novaDependencia.comprimento = Float.valueOf(et_Comprimento.getText().toString());
            break;
        case R.id.bt_AdDep2:
            novaDependencia.area = Float.valueOf(et_Area.getText().toString());
            novaDependencia.perimetro = Float.valueOf(et_Perimetro.getText().toString());
            break;
    }

    AlertDialog.Builder builder2 = new AlertDialog.Builder(v.getContext());
    builder2.setMessage("Deseja adicionar T.U.E. nesta dependência?").setPositiveButton("Sim", dialogClickListener).setNegativeButton("Não", dialogClickListener).show();
}

// Objeto tipo dialog criado para perguntar se usario deseja inserir TUEs
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                //Yes button clicked
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                Intent intent_NovaDep_CargasMin = new Intent(AdDep.this, CargasMin.class);
                intent_NovaDep_CargasMin.putExtra("novaDependencia", novaDependencia);
                startActivity(intent_NovaDep_CargasMin);
                break;
        }
    }
};

}

If anyone knows how to solve this, please share. Thanks.

1
  • Your requirement is not quite clear to me. Could you elaborate a bit? Commented Oct 8, 2015 at 5:40

1 Answer 1

3

The problem is that you're starting a new instance of the CargasMin activity from AdDep activity. Your AdDep activity should just finish and return a result back to the existing instance of CargasMin activity on the back stack for you to see all the previous list data as well.

To retrieve the new list item from AdDep as a result, use startActivityForResult()

case R.id.bt_AdDep_CargasMin:
    Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
    startActivityForResult(intent_AdDep, ADD_DEP_REQUEST);
    break;

where ADD_DEP_REQUEST is just a request code constant

public static final int ADD_DEP_REQUEST = 1;

Now, when AdDep is done collecting data, it returns the new data item as a result.

case DialogInterface.BUTTON_NEGATIVE:
    Intent result = new Intent();
    result.putExtra("novaDependencia", novaDependencia);
    setResult(Activity.RESULT_OK, result);
    finish();
    break;

Your main CargasMin activity will then receive the new data item as

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == ADD_DEP_REQUEST) {
         if (resultCode == RESULT_OK) {
             // Get last object created
             Dependencia dependenciaAAdicionar =
                         (Dependencia) data.getParcelableExtra("novaDependencia");
             if(dependenciaAAdicionar != null){
                 listaDeDependencias.add(dependenciaAAdicionar);
                 // Refresh Adapter pra mostrar dependenciaAAdicionar na ListView
                 adapterDeDependencias.notifyDataSetChanged();
             }
         }
     }
 }

Note that listaDeDependencias and adapterDeDependencias have been changed to instance members of the activity.

Your current approach would have worked if you were persisting the data to some storage (like in a file or database) but creating a new instance of CargasMin is still not recommended because the one existing on the back stack would suffice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.