Daniel
Daniel

Reputation: 125

How to pass a list of objects using intent?

How can I pass a list of objects to another activity ?

Im trying this and its not working...

Activity A

Intent i = new Intent(this,MainActivity.class);
i.putParcelableArrayListExtra("list",listCsv);
setResult(Activity.RESULT_OK,i);
finish();

Activity B

ArrayList<Contato> lAgenda = 
(ArrayList<Contato>) getIntent().getSerializableExtra("lista");

And in my Activity B my list lAgenda doesnt get the list of the Activity A, I got a NULL value.

My ContatoVO class

public class ContatoVO implements Serializable,Parcelable{
    private static final long serialVersionUID = 1L;
    private long id;
    private String nome;
    private String endereco;
    private String telefone;
    private String estado;
    private int idEstado;


        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public int getIdEstado()
        {
            return idEstado;
        }

        public void setIdEstado(int id)
        {
            this.idEstado = id;
        }

        public String getEstado() {
            return estado;
        }

        public void setEstado(String estado) {
            this.estado = estado;
        }

        public String getNome() {
            return nome;
        }

        public void setNome(String value) {
            this.nome = value;
        }

        public String getEndereco() {
            return endereco;
        }

        public void setEndereco(String value) {
            this.endereco = value;
        }

        public String getTelefone() {
            return telefone;
        }

        public void setTelefone(String value) {
            this.telefone = value;
        }
        // Will be used by the ArrayAdapter in the ListView
        @Override
        public String toString() {
            return nome;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {

            dest.writeString(nome);
            dest.writeString(endereco);
            dest.writeString(telefone);
        }

}

Function that sends data intent to Activity

public final void lerCsv(Context context)
    {

        AssetManager assetManager = context.getAssets();
        ArrayList<ContatoVO> listaCsv = new ArrayList<ContatoVO>();

        try
        {
            InputStream iStream = assetManager.open("teste.csv");
            InputStreamReader iStreamReader = new InputStreamReader(iStream);
            CSVReader csvReader = new CSVReader(iStreamReader,';');

            String[] registro = null;

            //pula cabeçalho
            csvReader.readNext();

            while((registro = csvReader.readNext()) != null)
            {

                ContatoVO contato = new ContatoVO();
                contato.setNome(registro[0]);
                contato.setEndereco(registro[1]);
                contato.setTelefone(registro[2]);

                listaCsv.add(contato);

            }

            csvReader.close();

            Intent i = new Intent(this,MainActivity.class);

            i.putParcelableArrayListExtra("lista",listaCsv);
            setResult(Activity.RESULT_OK,i);
            finish();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }

    }

Where i Try to get this data(list)

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ArrayList<ContatoVO> lAgendaVO = null;
        try {
            super.onActivityResult(requestCode, resultCode, data);

                lAgendaVO = data.getParcelableArrayListExtra("lista");

                lContatoDAO.open();     
                lContatoDAO.InserirListaCsv(lAgendaVO);
                adapter.notifyDataSetChanged();


        } catch (Exception ex) {
            trace("Erro : " + ex.getMessage());
        }
    }

Upvotes: 1

Views: 247

Answers (2)

Blackbelt
Blackbelt

Reputation: 157447

The key you are using to retrieve the ArrayList doesn't match the one you are using to write it onto the bundle. You have to be consistent. Use either list or lista. I strongly suggest you to use constants. E.g

ActivityA

public static final String LIST_KEY = "LIST_KEY";
Intent i = new Intent(this,MainActivity.class);
i.putParcelableArrayListExtra(LIST_KEY,listCsv);
setResult(Activity.RESULT_OK,i);
finish();

ActivityB

ArrayList<Contato> lAgenda = 
         (ArrayList<Contato>) getIntent(). getParcelableArrayList(ActivityA.LIST_KEY);

if the snippet to retrieve the List is part of onActivityResult, you have to use the former parameter Intent data instead of getIntent()

As Pointed out by @Sergey, you have to be consistent also on the put*/get* you use. If Contato is Parcelable (highly recommended), use getParcelableArrayList instead of getSerializableExtra .

Edit:

you need the constructor that takes a Parcel

protected ContatoVO(Parcel in) {
    id = in.readLong();
    nome = in.readString();
    endereco = in.readString();
    telefone = in.readString();
    estado = in.readString();
    idEstado = in.readInt();
}

you writeToParcel is not writing all the field. Change it to:

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeLong(id);
    dest.writeString(nome);
    dest.writeString(endereco);
    dest.writeString(telefone);
    dest.writeString(estado);
    dest.writeInt(idEstado);
}

And you missed Parcelable.Creator

@SuppressWarnings("unused")
public static final Parcelable.Creator<ContatoVO> CREATOR = new Parcelable.Creator<ContatoVO>() {
    @Override
    public ContatoVO createFromParcel(Parcel in) {
        return new ContatoVO(in);
    }

    @Override
    public ContatoVO[] newArray(int size) {
        return new ContatoVO[size];
    }
};

}

Upvotes: 5

michal.luszczuk
michal.luszczuk

Reputation: 2903

If you want to return result of startActivityForResult and you are using putParcelableArrayListExtra which uses ArrayList containing parcelable objects you shoud be consistent and when receiving data use

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      .... = data.getParcelableArrayListExtra("list")
}

Upvotes: 1

Related Questions