如何通过ArrayList< Object>从一个活动到另一个活动 [英] How do I pass ArrayList<Object> from one Activity to another Activity

查看:84
本文介绍了如何通过ArrayList< Object>从一个活动到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个对象的ArrayList从一个Activity传递到Activity.

I want to pass ArrayList of an Object from one Activity to Activity.

以下是示例代码:

{
    ArrayList<object> list=new ArrayList<>();

    Object value[]=new Object[m.size()];
    int n=0;

    value[]=new Object[n];
    value[n]=data.getName("name");
    value[n]=data.getLocation("location");

    list.add(value[n]);
    n++; //Since there are "n" number of object 
    
    }
    
    //here the value a which is ArrayList Object
    // which I want to pass it from here to another activity.

所以现在我该如何将对象从此处传递到另一个活动. 但是,我可以使用 Gson 获得价值. 通过将值转换为 json 并将其作为字符串传递给 SharedPreference 并从另一个活动中检索,然后使用 Type Json 转换回原始格式.

So now how will I pass the object from here to another activity. However, I am able to get the value using Gson. By converting the value to json and pass it as String to SharedPreference and retrieving from another activity then convert back from Json using the Type to back it's Original form.

我想知道是否可以使用 Parceable 传递值.因为我在使用它时会得到空值.

I want to know whether is it possible to pass the value using Parceable. Because I am getting null value when I used it.

这是我尝试使对象变量可设置的代码:

here is the code which I tried to make my Object variable Parceable:

public class ProductList implements Parcelable {

private String NAME;
private String LOCATION;

public ProductList() {
}

protected ProductList(Parcel in) {
    LOCATION= in.readString();
    NAME= in.readString();
   
}

public static final Creator<ProductList> CREATOR = new Creator<ProductList>() {
    @Override
    public ProductList createFromParcel(Parcel in) {
        return new ProductList(in);
    }

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

public String getNAME() {
    return NAME;
}
public void setNAME(String NAME) {
    this.NAME= NAME;
}
public String getLOCATION() {
    return LOCATION;
}
public void setITEM_IMAGE(String LOCATION) {
    this.LOCATION= LOCATION;
}
@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(NAME);
    dest.writeString(LOCATION);
}
}

推荐答案

请参阅此链接以进行理解.

活动一:

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
            ArrayList<object> list=new ArrayList<>();
            intent.putExtra("LIST", list);
            startActivity(intent);

第二项活动:

ArrayList<object> list = (ArrayList<object>)getIntent().getSerializableExtra("LIST");

还可以在您的自定义类中实现Serializable.

Also implement Serializable in your custom class.

public class ProductList implements Parcelable, Serializable

这篇关于如何通过ArrayList&lt; Object&gt;从一个活动到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆