我正在尝试从一个“活动”发送客户类的对象,并在另一个“”中显示它。
客户类别的代码:
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;
}
}
我想将其对象从一个“活动”发送到另一个“,然后在另一个活动”上显示数据。
我怎样才能做到这一点?
我写了一个名为intentparser的库
它真的很容易使用将此添加到项目等级
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
将此添加到应用程序等级
dependencies {
implementation 'com.github.lau1944:intentparser:v$currentVersion'
}
使用扩展方法putObject传递对象
val testModel = TestModel(
text = "hello world",
isSuccess = false,
testNum = 1,
textModelSec = TextModelSec("second model")
)
startActivity(
Intent(this, ActivityTest::class.java).apply {
this.putObject(testModel)
}
)
从上一个活动获取对象
val testModel = intent.getObject(TestModel::class.java)
我们可以将对象从一个活动传递到另一个活动:
SupplierDetails poSuppliersDetails = new SupplierDetails();
在poSuppliersDetails中,我们有一些价值观。现在我将此对象发送到目标活动:
Intent iPODetails = new Intent(ActivityOne.this, ActivityTwo.class);
iPODetails.putExtra("poSuppliersDetails", poSuppliersDetails);
如何在ACctivityTwo中实现这一点:
private SupplierDetails supplierDetails;
supplierDetails =(SupplierDetails) getIntent().getSerializableExtra("poSuppliersDetails");
调用活动时
Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);
在toClass.java中,通过
Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj");
请确保客户类实现parcelable
public class Customer implements Parcelable {
private String firstName, lastName, address;
int age;
/* all your getter and setter methods */
public Customer(Parcel in ) {
readFromParcel( in );
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public LeadData createFromParcel(Parcel in ) {
return new Customer( in );
}
public Customer[] newArray(int size) {
return new Customer[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(firstName);
dest.writeString(lastName);
dest.writeString(address);
dest.writeInt(age);
}
private void readFromParcel(Parcel in ) {
firstName = in .readString();
lastName = in .readString();
address = in .readString();
age = in .readInt();
}
以上答案几乎都是正确的,但对于那些不理解这些答案的人来说Android有一个强大的类Intent。借助它,您不仅可以在活动之间共享数据,还可以在Android的其他组件之间共享数据(广播接收器,我们使用ContetResolver类无Intent提供的内容服务)。在你的活动中,你建立了意图
Intent intent = new Intent(context,SomeActivity.class);
intent.putExtra("key",value);
startActivity(intent);
在接收活动中
public class SomeActivity extends AppCompactActivity {
public void onCreate(...){
...
SomeObject someObject = getIntent().getExtras().getParceable("key");
}
}
为了在活动之间共享,必须在对象上实现Parceable或Serializable接口。很难在对象上实现Parcealbe而不是Serializable接口,这就是为什么android有插件的原因,尤其是针对这一点。下载并使用它。