我正在尝试从一个“活动”发送客户类的对象,并在另一个“”中显示它。
客户类别的代码:
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;
}
}
我想将其对象从一个“活动”发送到另一个“,然后在另一个活动”上显示数据。
我怎样才能做到这一点?
一种选择是让自定义类实现Serializable接口,然后可以使用intent#putExtra()方法的putExtra变量(Serializable..)在intent extra中传递对象实例。
实际代码:
在自定义模型/对象类中:
public class YourClass implements Serializable {
在使用自定义模型/类的其他类中:
//To pass:
intent.putExtra("KEY_NAME", myObject);
myObject的类型为“YourClass”。然后,要从另一个活动中检索,请使用getSerializableExtra使用相同的Key名称获取对象。需要对YourClass进行类型转换:
// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");
注意:确保主自定义类的每个嵌套类都实现了Serializable接口,以避免任何序列化异常。例如:
class MainClass implements Serializable {
public MainClass() {}
public static class ChildClass implements Serializable {
public ChildClass() {}
}
}
创建自己的类Customer,如下所示:
import import java.io.Serializable;
public class Customer implements Serializable
{
private String name;
private String city;
public Customer()
{
}
public Customer(String name, String city)
{
this.name= name;
this.city=city;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city= city;
}
}
在onCreate()方法中
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top);
Customer cust=new Customer();
cust.setName("abc");
cust.setCity("xyz");
Intent intent=new Intent(abc.this,xyz.class);
intent.putExtra("bundle",cust);
startActivity(intent);
}
在xyz活动类中,您需要使用以下代码:
Intent intent=getIntent();
Customer cust=(Customer)intent.getSerializableExtra("bundle");
textViewName.setText(cust.getName());
textViewCity.setText(cust.getCity());
我创建了一个保存临时对象的单例助手类。
public class IntentHelper {
private static IntentHelper _instance;
private Hashtable<String, Object> _hash;
private IntentHelper() {
_hash = new Hashtable<String, Object>();
}
private static IntentHelper getInstance() {
if(_instance==null) {
_instance = new IntentHelper();
}
return _instance;
}
public static void addObjectForKey(Object object, String key) {
getInstance()._hash.put(key, object);
}
public static Object getObjectForKey(String key) {
IntentHelper helper = getInstance();
Object data = helper._hash.get(key);
helper._hash.remove(key);
helper = null;
return data;
}
}
不要将对象放在Intent中,而是使用IntentHelper:
IntentHelper.addObjectForKey(obj, "key");
在新的“活动”中,您可以获取对象:
Object obj = (Object) IntentHelper.getObjectForKey("key");
请记住,一旦加载,对象将被删除,以避免不必要的引用。