我正在尝试从一个“活动”发送客户类的对象,并在另一个“”中显示它。
客户类别的代码:
public class Customer {
private String firstName, lastName, address;
int age;
public Customer(String fname, String lname, int age, String address) {
firstName = fname;
lastName = lname;
age = age;
address = address;
}
public String printValues() {
String data = null;
data = "First Name :" + firstName + " Last Name :" + lastName
+ " Age : " + age + " Address : " + address;
return data;
}
}
我想将其对象从一个“活动”发送到另一个“,然后在另一个活动”上显示数据。
我怎样才能做到这一点?
我知道静态是不好的,但似乎我们不得不在这里使用它。parceables/seriazables的问题是两个活动具有相同对象的重复实例=内存和CPU的浪费。公共类IntentMailBox{静态队列<对象>content=newLinkedList<对象>();}
呼叫活动
IntentMailBox.content.add(level);
Intent intent = new Intent(LevelsActivity.this, LevelActivity.class);
startActivity(intent);
调用的活动(请注意,当系统销毁和重新创建活动时,可能会多次调用onCreate()和onResume())
if (IntentMailBox.content.size()>0)
level = (Level) IntentMailBox.content.poll();
else
// Here you reload what you have saved in onPause()
另一种方法是声明要在该类中传递的类的静态字段。它仅用于此目的。不要忘记,在onCreate中它可以为空,因为系统已经从内存中卸载了应用程序包,并在稍后重新加载。请记住,您仍然需要处理活动生命周期,您可能希望将所有数据直接写入共享的首选项,这对于复杂的数据结构来说是很痛苦的。
像这样创建自定义类:
public class Test implements Parcelable {
String message;
protected Test(Parcel in) {
message = in.readString();
}
public static final Creator<Test> CREATOR = new Creator<Test>() {
@Override
public Test createFromParcel(Parcel in) {
return new Test(in);
}
@Override
public Test[] newArray(int size) {
return new Test[size];
}
};
public String getMessage() {
return message;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(message);
}
使用Intent发送数据,如下所示:开始活动之前,必须设置一些数据
Intent intent = new Intent(context, PostDetailsActivity.class);
intent.putExtra("data", (Parcelable) test);
((context)).startActivity(intent);
从以下意图中获取数据:
Test test = (Test) getIntent().getParcelableExtra("data");
根据我的经验,有三种主要的解决方案,各有其缺点和优点:
实施Parcelable实现可串行化使用某种轻量级事件总线库(例如,Greenrobot的EventBus或Square的Otto)
Parcelable-快速且符合Android标准,但它有很多样板代码,并且需要硬编码字符串以供在提取意图值(非强类型)时参考。
可序列化-接近于零样板,但这是最慢的方法,并且在从意图中提取值(非强类型)时还需要硬编码字符串。
事件总线-零样板,最快的方法,不需要硬编码字符串,但它需要额外的依赖项(虽然通常很轻,约40 KB)
我发布了这三种方法的非常详细的比较,包括效率基准。