我创建了以下类并使用了此类的对象。我想传递这个类的列表并将其发送到下一个活动。
class contact implements Comparable<contact>, Parcelable {
String name;
private String phone;
private Bitmap image;
contact(String n, String p, Bitmap pic) {
super();
name = n;
phone = p;
image = pic;
}
public contact(Parcel in) {
String[] data = new String[3];
in.readStringArray(data);
this.name=data[0];
this.phone=data[1];
byte [] encodeByte= Base64.decode(data[2],Base64.DEFAULT);
this.image = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
}
public void setImage(Bitmap image) {
this.image = image;
}
Bitmap getImage() {
return image;
}
public void setName(String name) {
this.name = name;
}
String getName() {
return name;
}
public void setPhone(String phone) {
this.phone = phone;
}
String getPhone() {
return phone;
}
static Comparator<contact> ContactNameComparator
= new Comparator<contact>() {
public int compare(contact c1, contact c2) {
String name1 = c1.getName().toUpperCase();
String name2 = c2.getName().toUpperCase();
return name1.compareTo(name2);
}
};
@Override
public int compareTo(@NonNull contact o) {
return 0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[]{this.getName(),this.getPhone(),String.valueOf(getImage())});
}
public static final Creator<contact> CREATOR = new Creator<contact>(){
@Override
public contact createFromParcel(Parcel in) {
return new contact(in);
}
@Override
public contact[] newArray(int size) {
return new contact[size];
}
};
}
在我的MainActivity中,我正在创建一个列表
List<contact> c=new ArrayList<>();
在将一些对象添加到此列表后,我尝试通过putExtra()将其发送到下一个活动但是收到错误。 我试图通过这样的列表,
Intent intent=new Intent(getApplicationContext(),NextActivity.class);
intent.putExtra("VAR1", (Parcelable) c);
startActivity(intent);
在我的NextActivity.class中,我正在接收它,
Bundle bundle = getIntent().getExtras();
c = bundle.getParcelableArrayList("VAR1" );
运行应用程序后,我收到以下错误:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.os.Parcelable
我该如何解决这个问题?
答案 0 :(得分:1)
试试这个
来自通话活动的代码
Intent intent=new Intent(getApplicationContext(),NextActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("VAR1", arraylist);
intent.putExtras(bundle);
this.startActivity(intent);
被叫活动代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
ArrayList<contact> arraylist = bundle.getParcelableArrayList("VAR1");
}