将对象的 ArrayList 传递给新的 Activity

2024-04-17

我有一个对象的 ArrayList。 IEArrayList<ObjectName>.

我想将其传递给新的Activity。我尝试使用putParcelableArrayList但它与对象有问题。我删除了<ObjectName>部分来自变量的创建和方法的工作,但后来我得到 Eclipse 抱怨不安全的东西。

我该如何通过这个ArrayList<ObjectName>到一个新的活动

谢谢你的时间

EDIT我试过这个:

ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);

我收到以下错误:

The method `putParcelableArrayList(String, ArrayList<? extends Parcelable>)` in the type `Bundle` is not applicable for the arguments `(String, ArrayList<ObjectName>)`

EDIT2对象示例代码。我需要改变这个吗Parcelable上班?

public class ObjectName {
    private int value1;
    private int value2;
    private int value3;

    public ObjectName (int pValue1, int pValue2, int Value3) {
        value1 = pValue1;
        value2 = pValue2;
        value3 = pValue3;
    }

    // Get Statements for each value below
    public int getValue1() {
        return value1;
    } 
    // etc

你的对象类应该实现parcelable。下面的代码应该可以帮助您入门。

    public class ObjectName implements Parcelable {

    // Your existing code

        public ObjectName(Parcel in) {
            super(); 
            readFromParcel(in);
        }

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

            public ObjectName[] newArray(int size) {

                return new ObjectName[size];
            }

        };

        public void readFromParcel(Parcel in) {
          Value1 = in.readInt();
          Value2 = in.readInt();
          Value3 = in.readInt();

        }
        public int describeContents() {
            return 0;
        }

        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(Value1);
            dest.writeInt(Value2);  
            dest.writeInt(Value3);
       }
    }

要使用上述内容,请执行以下操作:

在“发送”活动中使用:

ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();  
Bundle bundle = new Bundle();  
bundle.putParcelableArrayList("arraylist", arraylist);

在“接收”活动中使用:

Bundle extras = getIntent().getExtras();  
ArrayList<ObjectName> arraylist  = extras.getParcelableArrayList("arraylist");  
ObjectName object1 = arrayList[0];

等等。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将对象的 ArrayList 传递给新的 Activity 的相关文章

随机推荐