我在一个应用程序中简历两个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();
} }
<?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>
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。