如何使用intent传递对象列表?

时间:2015-10-15 15:41:56

标签: android

如何将对象列表传递给另一个活动?

我正在尝试这个并且它不起作用......

活动A

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

活动B

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

在我的Activity B中,我的列表lAgenda没有获取Activity A的列表, 我得到了NULL值。

我的ContatoVO课程

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

}

将数据意图发送到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();
        }

    }

我试图获取此数据(列表)

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

2 个答案:

答案 0 :(得分:5)

用于检索ArrayList的密钥与您用于将其写入捆绑包的密钥不匹配。你必须保持一致。使用listlista。我强烈建议你使用常量。 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);

如果要检索List的代码段是onActivityResult的一部分,则必须使用以前的参数Intent data而不是getIntent()

正如@Sergey指出的那样,你必须在你使用的put * / get *上保持一致。如果ContatoParcelable(强烈推荐),请使用getParcelableArrayList代替getSerializableExtra

修改

你需要一个带Parcel

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

你写的ToParcel并没有写完所有的字段。将其更改为:

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

你错过了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];
    }
};

}

答案 1 :(得分:1)

如果您想要返回startActivityForResult的结果 并且您使用的putParcelableArrayListExtra使用包含 parcelable 对象的ArrayList,您应该保持一致并且在接收数据时使用

@Override

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