Java 在活动之间传递自定义对象?
如何在android中的活动之间传递自定义对象?我知道捆绑包,但我似乎看不到其中有任何功能。谁能给我举一个很好的例子吗?您应该实现Java 在活动之间传递自定义对象?,java,android,Java,Android,如何在android中的活动之间传递自定义对象?我知道捆绑包,但我似乎看不到其中有任何功能。谁能给我举一个很好的例子吗?您应该实现 链接到 给定在整个对象树中实现可序列化的对象密码状态,您可以将此对象传递给另一个活动,如下所示: private void launchManagePassword() { Intent i= new Intent(this, ManagePassword.class); // no param constructor PasswordState o
链接到 给定在整个对象树中实现可序列化的对象密码状态,您可以将此对象传递给另一个活动,如下所示:
private void launchManagePassword() {
Intent i= new Intent(this, ManagePassword.class); // no param constructor
PasswordState outState= new PasswordState(lengthKey,timeExpire,isValidKey,timeoutType,"",model.getIsHashPassword());
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outState);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_PASSWORD); // used for callback
}
包裹
可能会解决您的问题
将一个包裹
想象成一个基本类型(long、String、Double、int等)的“数组”(隐喻)如果自定义类仅由基本类型组成,则更改类声明,包括实现可包裹
您可以毫无困难地将可包裹的对象传递给意图(就像发送基本类型的对象一样)。在本例中,我有一个名为FarmData的可包裹自定义类(由长、字符串和双精度组成),我通过intent将其从一个活动传递到另一个活动
FarmData farmData = new FarmData();
// code that populates farmData - etc etc etc
Intent intent00 = new Intent(getApplicationContext(), com.example.yourpackage.yourclass.class);
intent00.putExtra("farmData",farmData);
startActivity(intent00);
但是找回它可能很棘手。接收意图的活动将检查是否随意图一起发送了一个附加包
Bundle extras = getIntent().getExtras();
FarmData farmData = new FarmData();
Intent intentIncoming = getIntent();
if(extras != null) {
farmData = (FarmData) intentIncoming.getParcelableExtra("farmData");// OK
}
使用Parcelable接口,您可以将自定义java对象传递到intent中 1) 实现类的Parcelable接口,如:
class Employee implements Parcelable
{
}
2) 将可包裹对象传递到目标中,如:
Employee mEmployee =new Employee();
Intent mIntent = new Intent(mContect,Abc.class);
mIntent.putExtra("employee", mEmployee);
startActivity(mIntent);
3) 将数据放入新的[Abc]活动中,如:
Intent mIntent = getIntent();
Employee mEmployee = (Employee )mIntent.getParcelableExtra("employee");
在活动之间传递对象或使对象对所有应用程序通用的一种简单方法是创建一个类扩展应用程序 以下是一个例子:
public class DadosComuns extends Application{
private String nomeUsuario="";
public String getNomeUsuario() {
return nomeUsuario;
}
public void setNomeUsuario(String str) {
nomeUsuario = str;
}
}
在所有其他活动中,只需实例化一个对象“DadosComuns”,将其声明为全局变量
private DadosComuns dadosComuns;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//dados comuns
dadosComuns = ((DadosComuns)getApplicationContext());
dadosComuns.setNomeUsuario("userNameTest"); }
实例化的所有其他活动dadosComuns=((dadosComuns)getApplicationContext())您可以访问getNomeUsuario()=“userNameTest”
在您的AndroidManifest.xml中,您需要
<application
android:name=".DadosComuns"
为什么不能以捆绑方式发送对象?我是说,为什么Android不支持它?所有的活动都在同一个过程中运行,所以支持它不是很容易吗?@Enigma我想我明白你的问题了。如果您的意思是在bundle中“传递对对象的引用”,那么这是一个坏主意,因为创建对象的活动可能会由于内存不足而被销毁,并且对象将丢失。如果存在对对象的引用,则不会被销毁!我认为应该有比垃圾收集更具技术性的东西,关于这个@EhsanMirsaeedi如果引用阻止对封闭对象进行垃圾收集,则表示内存泄漏。@Igor Filippov Link为death