将UserInfo对象序列化为字符串,然后再将其传递给putExtra()方法
时间: 2024-02-20 07:58:39 浏览: 29
可以使用Java中的序列化机制将UserInfo对象序列化为字符串,然后再将其传递给putExtra()方法。具体操作步骤如下:
1. 让UserInfo类实现Serializable接口,即在类声明处加上关键字implements Serializable。
2. 使用Java中的ObjectOutputStream类将UserInfo对象序列化为字符串,代码示例如下:
```
UserInfo userInfo = new UserInfo();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(userInfo);
String userInfoStr = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
```
3. 将序列化后的字符串userInfoStr作为参数传递给Intent对象的putExtra()方法,代码示例如下:
```
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("userInfo", userInfoStr);
startActivity(intent);
```
4. 在接收Intent的目标Activity中,使用Base64解码将序列化后的字符串转换为UserInfo对象,代码示例如下:
```
String userInfoStr = getIntent().getStringExtra("userInfo");
byte[] data = Base64.decode(userInfoStr, Base64.DEFAULT);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
UserInfo userInfo = (UserInfo) ois.readObject();
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)