开发者社区 问答 正文

求助:Intent复制ArrayList扩展类报错:ClassCastException:报错

我在一个应用程序中简历两个Activity:TestActivity和AnotherActivity。TestActivity创建Intent并将一个ArrayList的扩展类PlayList存入Intent,之后调用AnotherActivity,AnotherActivity从Intent中读取传入的PlayList,读取时会报错(ClassCastException),但如果使用ArrayList就没问题。记得文档中关于Serializable的描述是只要implement该接口就可以工作的,不需要事先objectWrite和objectRead方法,而且为什么报ClassCastException错误呢?而且我发现通过Intent单纯的传递ArrayList对象时没有问题的。

附上源码:

import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class TestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }

public void doClick(View v)
{
 PlayList al = new PlayList(this);
    al.add("XXX");
    al.add("YYY");
    al.add("ZZZ");
    Intent intent = new Intent(this, AnotherActivity.class);

Bundle bundle = new Bundle(); bundle.putSerializable("test",al); intent.putExtras(bundle); //intent.putExtra(PlayListManager.CURRENT_LIST_FILE_NAME, bundle); startActivity(intent); } }


import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; public class AnotherActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 PlayList temp = (PlayList)getIntent().getSerializableExtra("test");
    Log.v("AnotherActivity","temp: "+temp.size());
}

}


import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import android.content.Context; import android.util.AttributeSet; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class PlayList extends ArrayList<String> implements Serializable{

public PlayList(Context context) {
super();
} }

main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#FFFFFF" > <LinearLayout android:id="@+id/layout_top" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" > <Button android:id="@+id/button01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="test" android:onClick="doClick" > </Button> </LinearLayout> 

展开
收起
kun坤 2020-06-06 23:25:28 531 分享 版权
1 条回答
写回答
取消 提交回答
  •  (PlayList)(getIntent().getExtras()).getSerializable("test");

    2020-06-06 23:25:33
    赞同 展开评论