我有一个对象的arraylist.即ArrayList.
我想把它传递给一个新的Activity.我试图使用putParcelableArrayList,但它有对象的问题.我从变量的创建中删除了部分并且该方法有效,但后来我得到了eciplse抱怨不安全的东西.
如何将此arrayList传递给新的Activity
谢谢你的时间
编辑 我试过这个:
ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
The method putParcelableArrayList(String, ArrayList<? extends Parcelable>) in the type Bundle is not applicable for the arguments (String, ArrayList<ObjectName>)
Run Code Online (Sandbox Code Playgroud)
EDIT2 对象示例代码.我是否需要将此更改为paracbale才能工作?
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
Run Code Online (Sandbox Code Playgroud)
Man*_*del 47
您的对象类应该实现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);
}
}
Run Code Online (Sandbox Code Playgroud)
要使用上面这样做:
在'发送'活动中使用:
ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
Run Code Online (Sandbox Code Playgroud)
在'接收'活动中使用:
Bundle extras = getIntent().getExtras();
ArrayList<ObjectName> arraylist = extras.getParcelableArrayList("arraylist");
ObjectName object1 = arrayList[0];
Run Code Online (Sandbox Code Playgroud)
等等.
Man*_*rar 18
非常简单的方法,尝试以下方法:
bundle.putSerializable("lstContact", (Serializable) lstObject);
lstObj = (List<Contacts>) bundle.getSerializable("lstContact");
Run Code Online (Sandbox Code Playgroud)
您还需要从Serializable接口实现Contact类.例如:
public class Contact implements Serializable{
...
...
...
}
Run Code Online (Sandbox Code Playgroud)
don*_*ata 14
您有两种选择:
ArrayList中的对象Parceable根据方法的要求放置工具putParcelableArrayList ()
或者对象可以实现Serializable并使用该方法putSerializable()添加ArrayList,即bundle.putSerializable("arraylist", arraylist);
Android通过序列化和反序列化(通过Serializable或Parcelable)传递Bundle中的Object.因此,要在Bundle中传递的所有对象都必须实现这两个接口中的一个.
大多数对象很容易序列化,Serializable并且实现Serializable和向类添加静态UID比编写所需的所有方法/类要简单得多Parcelable.
| 归档时间: |
|
| 查看次数: |
52690 次 |
| 最近记录: |