我如何通过一个自定义类型的对象从一个活动到另一个使用类意图的putExtra()方法?


当前回答

第一个活动:

intent.putExtra("myTag", yourObject);

在你的第二篇文章中:

myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");

别忘了让你的自定义对象Serializable:

public class myCustomObject implements Serializable {
...
}

其他回答

我发现最简单的解决办法是… 创建带有getter和setter的静态数据成员的类。

从一个活动中设置并从另一个活动中获取该对象。

活动

mytestclass.staticfunctionSet("","",""..etc.);

活动b

mytestclass obj= mytestclass.staticfunctionGet();

在你的类模型(对象)实现Serializable中,用于 例子:

public class MensajesProveedor implements Serializable {

    private int idProveedor;


    public MensajesProveedor() {
    }

    public int getIdProveedor() {
        return idProveedor;
    }

    public void setIdProveedor(int idProveedor) {
        this.idProveedor = idProveedor;
    }


}

和你的第一项活动

MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
                i.putExtra("mensajes",mp);
                startActivity(i);

和你的第二个活动(NewActivity)

        MensajesProveedor  mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");

祝你好运! !

对于你知道要在应用程序中传递数据的情况,使用“全局变量”(比如静态类)

以下是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);
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);