我如何通过一个自定义类型的对象从一个活动到另一个使用类意图的putExtra()方法?
当前回答
快速需求的简短回答
1. 将类实现为可序列化的。
如果你有任何内部类,不要忘记将它们实现为Serializable !!
public class SportsData implements Serializable
public class Sport implements Serializable
List<Sport> clickedObj;
2. 将你的对象放入Intent中
Intent intent = new Intent(SportsAct.this, SportSubAct.class);
intent.putExtra("sport", clickedObj);
startActivity(intent);
3.并在另一个活动类中接收您的对象
Intent intent = getIntent();
Sport cust = (Sport) intent.getSerializableExtra("sport");
其他回答
对于你知道要在应用程序中传递数据的情况,使用“全局变量”(比如静态类)
以下是Dianne Hackborn (hackbod -谷歌安卓软件工程师)对此事的看法:
For situations where you know the activities are running in the same process, you can just share data through globals. For example, you could have a global HashMap<String, WeakReference<MyInterpreterState>> and when you make a new MyInterpreterState come up with a unique name for it and put it in the hash map; to send that state to another activity, simply put the unique name into the hash map and when the second activity is started it can retrieve the MyInterpreterState from the hash map with the name it receives.
从这个活动中启动另一个活动,通过Bundle对象传递参数
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
检索另一个活动(YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
这对于简单类型数据类型是可以的。 但是如果你想在活动之间传递复杂的数据,你需要先序列化它。
这里我们有员工模型
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
可以使用谷歌提供的Gson lib对复杂数据进行序列化 像这样
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
您需要将对象序列化为某种字符串表示形式。一种可能的字符串表示是JSON,如果你问我,在android中序列化JSON最简单的方法之一是通过谷歌GSON。
在这种情况下,你只需要输入字符串返回值from (new Gson()).toJson(myObject);并检索字符串值并使用fromJson将其转换回您的对象。
但是,如果您的对象不是非常复杂,那么可能不值得这样做,您可以考虑传递对象的单独值。
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
我也遇到过同样的问题。我通过使用一个静态类来解决这个问题,在HashMap中存储我想要的任何数据。在上面,我使用了标准活动类的扩展,其中我覆盖了onCreate和onDestroy方法来做数据传输和数据清除隐藏。一些荒谬的设置必须改变,例如方向处理。
注释: 不提供一般对象传递给另一个活动是痛苦的屁股。这就像射击自己的膝盖,希望赢得100米。“比喻”并不是一个充分的替代品。这让我笑了……我不想实现这个接口到我的技术自由API,因为我更不想引入一个新的层…这是怎么回事,我们在移动编程中离现代范式如此之远……
推荐文章
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的