Pass object of an activity to another Android

0

I'm looking for a way to pass an object to another activity.

What I do is create it in an activity. And in the other I want to receive it and work with it. Try passing data by object data with intent.putExtra() but it is not the most practical way to work.

Here is an example:

i.putExtra("nombre", jsonObject.optString("name"));
i.putExtra("apellido", jsonObject.optString("lastname"));
i.putExtra("telefono", jsonObject.optString("phone"));
i.putExtra("direccion", jsonObject.optString("address"));
i.putExtra("email", jsonObject.optString("usuario"));

And in the other activity I believe it:

usuario.setNombre(getIntent().getStringExtra("nombre"));
usuario.setApellido(getIntent().getStringExtra("apellido"));
usuario.setDireccion(getIntent().getStringExtra("direccion"));
usuario.setEmail(getIntent().getStringExtra("email"));
usuario.setTelefono(getIntent().getStringExtra("telefono"));

I would like to create it in the first activity and pass it as an object instead of passing data by data. Thanks.

    
asked by Juampi 29.11.2018 в 15:06
source

1 answer

1

The User class must implement the Serializable interface:

public class Usuario implements Serializable{
    .
    .
    .
    public void Usuario(){};
    //Metodos y constructores
    .
    .
    .
}

And to pass it by intent, you must pass it as a simple extra.

intent.putExtra("nombre_del_identificador", referenciaDeUsuario// O simplemente usuario);

To retrieve the object in an Activity:

getIntent().getSerializableExtra("nombre_del_identificador");

With the above you can create a User type reference in Activity B and thus be able to use its attributes as you wish.

Observation: This method is very good for small objects such as User, do not try to pass huge amounts of data through the implementation of Serializable.

    
answered by 29.11.2018 / 15:34
source