Android Activity传递大list的实现方法
介绍
在Android开发中,有时我们需要在不同的Activity之间传递一些数据。对于较小的数据,我们可以使用Intent的putExtra()方法来传递。但是,当我们需要传递较大的数据,比如一个大list时,我们需要使用其他的方法来实现。
本文将介绍如何在Android Activity之间传递大list,并提供详细的步骤和示例代码。
总体流程
下面是实现这个功能的整体流程:
步骤 | 描述 |
---|---|
1 | 准备一个包含大list的数据对象 |
2 | 在发送方Activity中将数据对象转换为字节数组 |
3 | 使用Intent传递字节数组给接收方Activity |
4 | 在接收方Activity中将字节数组转换回数据对象 |
代码示例
数据对象
首先,我们需要创建一个包含大list的数据对象。在这个例子中,我们创建了一个名为DataObject
的类,它有一个名为list
的属性,用于存储大list。
public class DataObject implements Serializable {
private List<String> list;
public DataObject(List<String> list) {
this.list = list;
}
public List<String> getList() {
return list;
}
}
发送方Activity
在发送方Activity中,我们需要将数据对象转换为字节数组,并使用Intent传递给接收方Activity。
public class SenderActivity extends AppCompatActivity {
private Button sendButton;
private List<String> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sender);
sendButton = findViewById(R.id.send_button);
// 初始化数据列表
dataList = new ArrayList<>();
dataList.add("Item 1");
dataList.add("Item 2");
dataList.add("Item 3");
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 将数据对象转换为字节数组
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(new DataObject(dataList));
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] byteArray = bos.toByteArray();
// 使用Intent传递字节数组给接收方Activity
Intent intent = new Intent(SenderActivity.this, ReceiverActivity.class);
intent.putExtra("data", byteArray);
startActivity(intent);
}
});
}
}
接收方Activity
在接收方Activity中,我们需要将接收到的字节数组转换回数据对象,然后可以使用其中的大list。
public class ReceiverActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
textView = findViewById(R.id.text_view);
// 接收传递过来的字节数组
Intent intent = getIntent();
byte[] byteArray = intent.getByteArrayExtra("data");
// 将字节数组转换为数据对象
DataObject dataObject = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
ObjectInputStream ois = new ObjectInputStream(bis);
dataObject = (DataObject) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 使用数据对象中的大list
if (dataObject != null) {
List<String> dataList = dataObject.getList();
StringBuilder stringBuilder = new StringBuilder();
for (String item : dataList) {
stringBuilder.append(item).append("\n");
}
textView.setText(stringBuilder.toString());
}
}
}
类图
下面是本文介绍的类的类图:
classDiagram
class DataObject {
- list: List<String>
+ DataObject(List<String>)
+ getList(): List<String>
}
饼状图
下面是本文介绍的流程的饼状图:
pie
"准备数据对象" : 1
"转换为字节数组" : 1
"使用Intent传递" : 1
"接收字节数组" : 1
"转换回数据对象" : 1