前言:平时都是传递int或者string数据,这次需要传递List数据,记录一下方法
最开始是使用Bundle来传递,这种方法网上有很多教程,就不写了。一开始是成功的,确实是可以传递,但是过了几天我再打开的时候,对数据进行了修改后就失败了。于是换了个方法。
记录一下方法和示例代码,示例代码是上面链接的文章里的
1、创建实体类Bean,同时Bean要implements Serializable:
package com.example.intentlist;
import java.io.Serializable;
public class Bean implements Serializable {
private int id;
private String name;
private int age;
public Bean() {
}
public Bean(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2、要传递的Activity:
package com.example.intentlist;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
List<Bean> lstBean;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstBean = new ArrayList<Bean>();
Bean bean = new Bean(1, "张三", 12);
lstBean.add(bean);
Bean bean1 = new Bean(2, "李四", 13);
lstBean.add(bean1);
Bean bean2 = new Bean(3, "王五", 14);
lstBean.add(bean2);
Bean bean3 = new Bean(4, "赵六", 15);
lstBean.add(bean3);
((Button) findViewById(R.id.btn_next)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intentPut = new Intent(MainActivity.this, IntentTestActivity.class);
intentPut.putExtra("lstBean", (Serializable) lstBean);
startActivity(intentPut);
}
});
}
}
3、接收list的Activity:
package com.example.intentlist;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class IntentTestActivity extends ActionBarActivity {
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_test);
Intent intentGet = getIntent();
List<Bean> lstBean = (List<Bean>) intentGet.getSerializableExtra("lstBean");
String result = "IntentTestActivity" + "\n";
for (Bean bean : lstBean) {
result += bean.getId() + "---" + bean.getName() + "---" + bean.getAge() + "\n";
}
((TextView) findViewById(R.id.tv_result)).setText(result);
}
}