我有自己的对象SineWave
我需要从SettingsActivity
传递到SimulationActivity
但是当我将SineWave []转换为Parceable []时,它会产生classcastexception。
SineWave对象: -
public class SineWave implements Parcelable{
float A,k,w,phi,VELOCITY;
int waveNum;
boolean plot;
public SineWave(Parcel in){
A=in.readFloat();
k=in.readFloat();
w=in.readFloat();
phi=in.readFloat();
VELOCITY=in.readFloat();
waveNum=in.readInt();
plot=in.readInt()==1;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeFloat(A);
out.writeFloat(k);
out.writeFloat(w);
out.writeFloat(phi);
out.writeFloat(VELOCITY);
out.writeInt(waveNum);
out.writeInt(plot ? 1 : 0);
}
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
public SineWave createFromParcel(Parcel in) {
return new SineWave(in);
}
public SineWave[] newArray(int size) {
return new SineWave[size];
}
};
}
设置活动: -
waveList = new ArrayList<SineWave>();
@Override
public void onClick(View view){
switch(view.getId()){
case R.id.start:
Intent i1 = new Intent();
i1.setClass(this, SimulationActivity.class);
i1.putExtra("list",(Parcelable[])(waveList.toArray()));
//Gives ClassCastException at above line
startActivity(i1);
break;
case R.id.add_wave:
...
break;
default: break;
}
}
SimulationActivity: -
public void onCreate(Bundle icicle){
...
Intent i = getIntent();
SineWave[] waveList[]=(SineWave[])i.getParcelableArrayExtra("list");
...
}
错误堆栈跟踪: -
Caused by: java.lang.ClassCastException: [Ljava.lang.Object;
at com.meet.simulators.wavesonstringsimulator.SettingsActivity.onClick(SettingsActivity.java:37) at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at android.view.View$1.onClick(View.java:2139)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
无法理解问题是什么?请帮助。
答案 0 :(得分:1)
您不能将对象数组(waveList.toArray()提供的对象)直接转换为另一种类型的数组。您只需要转换为SineWave,因为它已经是Parcelable。我相信这就是你能做到的:
i1.putExtra("list", waveList.toArray(new SineWave[waveList.size()]));
有关信息,putExtra的文档说明:
将扩展数据添加到intent中。名称必须包含包前缀,例如app com.android.contacts将使用“com.android.contacts.ShowAll”之类的名称。
我不知道可能会产生什么影响,但您可能还需要在“列表”前面添加您的包名称。