¿Cómo enviar un objeto de una actividad de Android a otra usando Intents?


¿Cómo puedo pasar un objeto de un tipo personalizado de una Actividad a otra usando el método putExtra() de la clase Intent?

Author: UMAR, 2010-01-26

30 answers

Si solo estás pasando objetos entonces Parcelable fue diseñado para esto. Requiere un poco más de esfuerzo de usar que usar la serialización nativa de Java, pero es mucho más rápido (y me refiero a manera, CAMINO más rápido).

De los documentos, un ejemplo sencillo de cómo implementar es:

// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
    private int mData;

    /* everything below here is for implementing Parcelable */

    // 99.9% of the time you can just ignore this
    @Override
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

Observe que en el caso de que tenga más de un campo para recuperar de un Paquete dado, debe hacerlo en el mismo orden en que los puso (es decir, en un FIFO enfoque).

Una vez que tienes tus objetos implementados Parcelable es solo cuestión de ponerlos en tus Intentos con putExtra():

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

Luego puedes sacarlos de nuevo con getParcelableExtra():

Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");

Si su Clase de objeto implementa Parcelable y Serializable, asegúrese de hacer cast a uno de los siguientes:

i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);
 692
Author: Jeremy Logan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-14 16:13:19

Necesitará serializar su objeto en algún tipo de representación de cadena. Una posible representación de cadena es JSON, y una de las formas más fáciles de serializar a/desde JSON en Android, si me preguntas, es a través de Google GSON.

En ese caso, debe poner el valor de retorno de la cadena desde (new Gson()).toJson(myObject); y recuperar el valor de la cadena y usar fromJson para volver a convertirlo en su objeto.

Si su objeto no es muy complejo, sin embargo, podría no valer la pena la sobrecarga, y podría considere pasar los valores separados del objeto en su lugar.

 165
Author: David Hedlund,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-26 12:24:06

Puede enviar un objeto serializable a través de intent

// send where details is object
ClassName details = new ClassName();
Intent i = new Intent(context, EditActivity.class);
i.putExtra("Editing", details);
startActivity(i);


//receive
ClassName model = (ClassName) getIntent().getSerializableExtra("Editing");

And 

Class ClassName implements Serializable {
} 
 142
Author: Sridhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-18 05:58:16

Para situaciones en las que sepa que pasará datos dentro de una aplicación, use "globales" (como clases estáticas)

Aquí es lo que Dianne Hackborn (hackbod-un Ingeniero de Software de Google Android) tenía que decir sobre el asunto:

Para situaciones en las que sabe que las actividades se ejecutan en el mismo proceso, solo puede compartir datos a través de globales. Por ejemplo, usted podría tener un HashMap<String, WeakReference<MyInterpreterState>> y cuando usted hace un nuevo MyInterpreterState vienen con un nombre único para ello y ponerlo en el mapa hash; para enviar ese estado a otro actividad, simplemente poner el nombre único en el mapa hash y cuando el segunda actividad se inicia se puede recuperar el MyInterpreterState de el mapa hash con el nombre que recibe.

 63
Author: Peter Ajtai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-03 13:48:57

Su clase debe implementar Serializable o Parcelable.

public class MY_CLASS implements Serializable

Una vez hecho esto, puede enviar un objeto en putExtra

intent.putExtra("KEY", MY_CLASS_instance);

startActivity(intent);

Para conseguir extras solo tienes que hacer

Intent intent = getIntent();
MY_CLASS class = (MY_CLASS) intent.getExtras().getSerializable("KEY");

Si su clase implementa el uso parcelable siguiente

MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");

Espero que ayude: D

 46
Author: Pedro Romão,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-23 09:58:12

Si su clase de objeto implementa Serializable, no necesitas hacer nada más, puedes pasar un objeto serializable.
eso es lo que uso.

 27
Author: Vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-24 19:56:41

Respuesta corta para la necesidad rápida

1. Implemente su Clase a Serializable.

Si tienes clases internas no olvides implementarlas en Serializable también!!

public class SportsData implements  Serializable
public class Sport implements  Serializable

List<Sport> clickedObj;

2. Ponga su objeto en la intención

 Intent intent = new Intent(SportsAct.this, SportSubAct.class);
            intent.putExtra("sport", clickedObj);
            startActivity(intent);

3. Y recibe tu objeto en la otra Clase de Actividad

Intent intent = getIntent();
    Sport cust = (Sport) intent.getSerializableExtra("sport");
 26
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-04 09:43:00

Puedes usar android BUNDLE para hacer esto.

Crea un Paquete de tu clase como:

public Bundle toBundle() {
    Bundle b = new Bundle();
    b.putString("SomeKey", "SomeValue");

    return b;
}

Luego pasa este paquete con INTENCIÓN. Ahora puede recrear su objeto de clase pasando bundle como

public CustomClass(Context _context, Bundle b) {
    context = _context;
    classMember = b.getString("SomeKey");
}

Declare esto en su clase personalizada y use.

 16
Author: om252345,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-15 02:31:18

Gracias por la ayuda parcelable, pero encontré una solución opcional más

 public class getsetclass implements Serializable {
        private int dt = 10;
    //pass any object, drwabale 
        public int getDt() {
            return dt;
        }

        public void setDt(int dt) {
            this.dt = dt;
        }
    }

En la Actividad Uno

getsetclass d = new getsetclass ();
                d.setDt(50);
                LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
                obj.put("hashmapkey", d);
            Intent inew = new Intent(SgParceLableSampelActivity.this,
                    ActivityNext.class);
            Bundle b = new Bundle();
            b.putSerializable("bundleobj", obj);
            inew.putExtras(b);
            startActivity(inew);

Obtener Datos En La Actividad 2

 try {  setContentView(R.layout.main);
            Bundle bn = new Bundle();
            bn = getIntent().getExtras();
            HashMap<String, Object> getobj = new HashMap<String, Object>();
            getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
            getsetclass  d = (getsetclass) getobj.get("hashmapkey");
        } catch (Exception e) {
            Log.e("Err", e.getMessage());
        }
 15
Author: user1140237,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-25 16:47:34

Implemente serializable en su clase

        public class Place implements Serializable{
        private int id;
        private String name;

        public void setId(int id) {
           this.id = id;
        }
        public int getId() {
           return id;
        }
        public String getName() {
           return name;
        }

        public void setName(String name) {
           this.name = name;
        }
        }

Entonces puede pasar este objeto en intent

     Intent intent = new Intent(this, SecondAct.class);
     intent.putExtra("PLACE", Place);
     startActivity();

En la segunda actividad puedes obtener datos como este

     Place place= (Place) getIntent().getSerializableExtra("PLACE");

Pero cuando los datos se vuelven grandes,este método será lento.

 15
Author: Ishan Fernando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-22 06:18:49

Hay un par de formas por las que puede acceder a variables u objetos en otras clases o Actividades.

A. Base de datos

B. preferencias compartidas.

C. Serialización de objetos.

D. Una clase que puede contener datos comunes puede ser nombrada como Utilidades Comunes que depende de usted.

E. Pasar datos a través de Intents e Interfaz Parcelable.

Depende de las necesidades de su proyecto.

A. Base de datos

SQLite es una base de datos de Código abierto que está incrustado en Android. SQLite admite funciones de base de datos relacionales estándar como sintaxis SQL, transacciones y declaraciones preparadas.

Tutoriales -- http://www.vogella.com/articles/AndroidSQLite/article.html

B. Preferencias compartidas

Supongamos que desea almacenar el nombre de usuario. Así que ahora habrá dos cosas: Clave Nombre de usuario, Valor Valor.

Conservación de

 // Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
 //now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();
 //put your value
 editor.putString("userName", "stackoverlow");

 //commits your edits
 editor.commit();

Usando putString(),putBoolean(),putInt(),putFloat (), putLong () puede guardar el dtatype deseado.

Cómo obtener

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

Http://developer.android.com/reference/android/content/SharedPreferences.html

C. Serialización De Objetos

La serlización de objetos se usa si queremos guardar un estado de objeto para enviarlo a través de la red o también puede usarlo para su propósito.

Use java beans y almacene en él como uno de sus campos y use para eso

Los JavaBeans son clases Java que tienen propiedades. Piensa en propiedades como variables de instancia privada. Ya que son privados, la única manera se puede acceder a ellos desde fuera de su clase a través de métodos en la clase. El los métodos que cambian el valor de una propiedad se llaman métodos setter, y los métodos que recuperan el valor de una propiedad se llaman métodos getter.

public class VariableStorage implements Serializable  {

    private String inString ;

    public String getInString() {
        return inString;
    }

    public void setInString(String inString) {
        this.inString = inString;
    }


}

Establezca la variable en su método de correo usando

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

Luego use serialización de objetos para serializar este objeto y en su otra clase deserializar este objeto.

En la serialización, un objeto puede ser representado como una secuencia de bytes que incluye los datos del objeto, así como información sobre el tipo del objeto y los tipos de datos almacenados en el objeto.

Después de que un objeto serializado se ha escrito en un archivo, se puede leer desde el archivo y deserializar, es decir, la información de tipo y los bytes que representan el objeto y sus datos pueden ser se utiliza para recrear el objeto en la memoria.

Si desea tutorial para esto consulte este enlace

Http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

Obtener variable en otras clases

D. Usos comunes

Puede crear una clase por su cuenta que puede contener datos comunes que necesita con frecuencia en su proyecto.

Muestra

public class CommonUtilities {

    public static String className = "CommonUtilities";

}

E. Pasar datos a través de Intents

Por favor, consulte este tutorial para esta opción de pasar datos.

Http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

 14
Author: Nikhil Agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:44

Utilizo Gson con su api tan potente y simple para enviar objetos entre actividades,

Ejemplo

// This is the object to be sent, can be any object
public class AndroidPacket {

    public String CustomerName;

   //constructor
   public AndroidPacket(String cName){
       CustomerName = cName;
   }   
   // other fields ....


    // You can add those functions as LiveTemplate !
    public String toJson() {
        Gson gson = new Gson();
        return gson.toJson(this);
    }

    public static AndroidPacket fromJson(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, AndroidPacket.class);
    }
}

2 funciones las añade a los objetos que desea enviar

Uso

Enviar objeto De A a B

    // Convert the object to string using Gson
    AndroidPacket androidPacket = new AndroidPacket("Ahmad");
    String objAsJson = androidPacket.toJson();

    Intent intent = new Intent(A.this, B.class);
    intent.putExtra("my_obj", objAsJson);
    startActivity(intent);

Recibir En B

@Override
protected void onCreate(Bundle savedInstanceState) {        
    Bundle bundle = getIntent().getExtras();
    String objAsJson = bundle.getString("my_obj");
    AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);

    // Here you can use your Object
    Log.d("Gson", androidPacket.CustomerName);
}

Lo uso casi en todos los proyectos que hago y no tengo problemas de rendimiento.

 12
Author: MBH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-26 12:40:06

Luché con el mismo problema. Lo resolví usando una clase estática, almacenando cualquier dato que quiera en un HashMap. En la parte superior uso una extensión de la clase de actividad estándar donde he anulado los métodos onCreate an onDestroy para hacer el transporte de datos y el borrado de datos ocultos. Algunos ajustes ridículos tienen que ser cambiados, por ejemplo, el manejo de la orientación.

Anotación: No proporcionar objetos generales para pasar a otra actividad es un dolor en el culo. Es como dispararse en la rodilla y con la esperanza de ganar 100 metros. "Parcable" no es un sustituto suficiente. Me hace reír... No quiero implementar esta interfaz a mi API libre de tecnología, ya que menos quiero introducir una nueva capa... ¿Cómo podría ser, que estamos en la programación móvil tan lejos del paradigma moderno...

 9
Author: oopexpert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-10 23:13:34

En tu primera Actividad:

intent.putExtra("myTag", yourObject);

Y en el segundo:

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

No olvide hacer serializable su objeto personalizado:

public class myCustomObject implements Serializable {
...
}
 9
Author: Rudi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-19 08:35:38

Otra forma de hacer esto es usar el objeto Application (android.app.Aplicación). Usted define esto en su archivo AndroidManifest.xml como:

<application
    android:name=".MyApplication"
    ...

Luego puede llamar a esto desde cualquier actividad y guardar el objeto en la clase Application.

En la Primeractividad:

MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);

En la Secondactividad, haz:

MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);

Esto es útil si tiene objetos que tienen alcance de nivel de aplicación, es decir, deben usarse en toda la aplicación. El método Parcelable es aún mejor si quieres control explícito sobre el ámbito del objeto o si el ámbito es limitado.

Esto evita el uso de Intents por completo, sin embargo. No se si te quedan bien. Otra forma de usar esto es hacer que los identificadores int de los objetos envíen a través de intents y recuperen los objetos que tengo en Maps en el objeto Application.

 7
Author: Saad Farooq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-18 23:11:38

En su modelo de clase (Objeto) implementar Serializable, para Ejemplo:

public class MensajesProveedor implements Serializable {

    private int idProveedor;


    public MensajesProveedor() {
    }

    public int getIdProveedor() {
        return idProveedor;
    }

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


}

Y su primera Actividad

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

Y su segunda Actividad (NewActivity)

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

¡Buena suerte!!

 6
Author: David Hackro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-26 01:22:22
public class SharedBooking implements Parcelable{

    public int account_id;
    public Double betrag;
    public Double betrag_effected;
    public int taxType;
    public int tax;
    public String postingText;

    public SharedBooking() {
        account_id = 0;
        betrag = 0.0;
        betrag_effected = 0.0;
        taxType = 0;
        tax = 0;
        postingText = "";
    }

    public SharedBooking(Parcel in) {
        account_id = in.readInt();
        betrag = in.readDouble();
        betrag_effected = in.readDouble();
        taxType = in.readInt();
        tax = in.readInt();
        postingText = in.readString();
    }

    public int getAccount_id() {
        return account_id;
    }
    public void setAccount_id(int account_id) {
        this.account_id = account_id;
    }
    public Double getBetrag() {
        return betrag;
    }
    public void setBetrag(Double betrag) {
        this.betrag = betrag;
    }
    public Double getBetrag_effected() {
        return betrag_effected;
    }
    public void setBetrag_effected(Double betrag_effected) {
        this.betrag_effected = betrag_effected;
    }
    public int getTaxType() {
        return taxType;
    }
    public void setTaxType(int taxType) {
        this.taxType = taxType;
    }
    public int getTax() {
        return tax;
    }
    public void setTax(int tax) {
        this.tax = tax;
    }
    public String getPostingText() {
        return postingText;
    }
    public void setPostingText(String postingText) {
        this.postingText = postingText;
    }
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(account_id);
        dest.writeDouble(betrag);
        dest.writeDouble(betrag_effected);
        dest.writeInt(taxType);
        dest.writeInt(tax);
        dest.writeString(postingText);

    }

    public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
    {
        public SharedBooking createFromParcel(Parcel in)
        {
            return new SharedBooking(in);
        }
        public SharedBooking[] newArray(int size)
        {
            return new SharedBooking[size];
        }
    };

}

Pasando los datos:

Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
intent.putExtras(bundle);
startActivity(intent);

Recuperando los datos:

Bundle bundle = getIntent().getExtras();
dataList2 = getIntent().getExtras().getParcelableArrayList("data");
 6
Author: Adnan Abdollah Zaki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-08 21:38:55

La solución más fácil que encontré es.. para crear una clase con miembros de datos estáticos con getters setters.

Establecer desde una actividad y obtener desde otra actividad ese objeto.

Actividad A

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

Actividad b

mytestclass obj= mytestclass.staticfunctionGet();
 5
Author: UMAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-04 12:07:22

Puede usar putExtra(Serializable..) y getSerializableExtra () métodos para pasar y recuperar objetos de tu tipo de clase; tendrás que marcar tu clase Serializable y asegurarte de que todas tus variables miembro también sean serializables...

 4
Author: null,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-06 16:00:09

Crear Aplicación Android

Archivo >> Nuevo > > Aplicación Android

Introduzca el nombre del proyecto: android-pass-object-to-activity

Pakcage: com.hmkcode.android

Mantenga otras selecciones defualt, vaya a continuación hasta que llegue a Finish

Antes de comenzar a crear la Aplicación necesitamos crear la clase POJO "Person" que usaremos para enviar objetos de una actividad a otra. Observe que la clase está implementando Serializable interfaz.

Persona.java

package com.hmkcode.android;
import java.io.Serializable;

public class Person implements Serializable{

    private static final long serialVersionUID = 1L;

    private String name;
    private int age;

        // getters & setters....

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }   
}

Dos Diseños para Dos Actividades

Activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/tvName"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_horizontal"
        android:text="Name" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:ems="10" >
        <requestFocus />
    </EditText>
</LinearLayout>

<LinearLayout
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
<TextView
    android:id="@+id/tvAge"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center_horizontal"
    android:text="Age" />
<EditText
    android:id="@+id/etAge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10" />
</LinearLayout>

<Button
    android:id="@+id/btnPassObject"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Pass Object to Another Activity" />

</LinearLayout>

Actividad_anotra.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
 >

<TextView
    android:id="@+id/tvPerson"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_gravity="center"
    android:gravity="center_horizontal"
 />

</LinearLayout>

Dos Clases de Actividad

1) Actividad principal.java

package com.hmkcode.android;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {

Button btnPassObject;
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnPassObject = (Button) findViewById(R.id.btnPassObject);
    etName = (EditText) findViewById(R.id.etName);
    etAge = (EditText) findViewById(R.id.etAge);

    btnPassObject.setOnClickListener(this);
}

@Override
public void onClick(View view) {

    // 1. create an intent pass class name or intnet action name 
    Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");

    // 2. create person object
    Person person = new Person();
    person.setName(etName.getText().toString());
    person.setAge(Integer.parseInt(etAge.getText().toString()));

    // 3. put person in intent data
    intent.putExtra("person", person);

    // 4. start the activity
    startActivity(intent);
}

}

2) Otra actividad.java

package com.hmkcode.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class AnotherActivity extends Activity {

TextView tvPerson;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_another);

    // 1. get passed intent 
    Intent intent = getIntent();

    // 2. get person object from intent
    Person person = (Person) intent.getSerializableExtra("person");

    // 3. get reference to person textView 
    tvPerson = (TextView) findViewById(R.id.tvPerson);

    // 4. display name & age on textView 
    tvPerson.setText(person.toString());

}
}
 3
Author: MFP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-27 05:53:41
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
 3
Author: Manas Ranjan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-16 09:51:17

Sé que esto es tarde, pero es muy simple.Todo lo que tiene que hacer es dejar que su clase implemente Serializable como

public class MyClass implements Serializable{

}

Entonces puedes pasar a una intent como

Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);

Para conseguirlo simplemente llama

MyClass objec=(MyClass)intent.getExtra("theString");
 3
Author: suulisin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-13 12:44:02

Usando la biblioteca Gson de Google puedes pasar objetos a otras actividades.En realidad, convertiremos el objeto en forma de cadena json y después de pasar a otra actividad volveremos a convertirlo a un objeto como este

Considere una clase de frijol como esta

 public class Example {
    private int id;
    private String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Necesitamos pasar el objeto de la clase de ejemplo

Example exampleObject=new Example(1,"hello");
String jsonString = new Gson().toJson(exampleObject);
Intent nextIntent=new Intent(this,NextActivity.class);
nextIntent.putExtra("example",jsonString );
startActivity(nextIntent);

Para leer necesitamos hacer la operación inversa en NextActivity

 Example defObject=new Example(-1,null);
    //default value to return when example is not available
    String defValue= new Gson().toJson(defObject);
    String jsonString=getIntent().getExtras().getString("example",defValue);
    //passed example object
    Example exampleObject=new Gson().fromJson(jsonString,Example .class);

Agregue esta dependencia en gradle

compile 'com.google.code.gson:gson:2.6.2'
 3
Author: Jinesh Francis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-07 04:57:11

Lo más simple sería simplemente usar lo siguiente donde el elemento es una cadena:

intent.putextra("selected_item",item)

Para recibir:

String name = data.getStringExtra("selected_item");
 2
Author: ankish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-01 20:20:58

Si tiene una clase singleton (Servicio fx) que actúa como puerta de enlace a su capa de modelo de todos modos, se puede resolver teniendo una variable en esa clase con getters y setters para ella.

En la Actividad 1:

Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);

En la Actividad 2:

private Service service;
private Order order;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quality);

    service = Service.getInstance();
    order = service.getSavedOrder();
    service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}

En servicio:

private static Service instance;

private Service()
{
    //Constructor content
}

public static Service getInstance()
{
    if(instance == null)
    {
        instance = new Service();
    }
    return instance;
}
private Order savedOrder;

public Order getSavedOrder()
{
    return savedOrder;
}

public void setSavedOrder(Order order)
{
    this.savedOrder = order;
}

Esta solución no requiere ninguna serialización u otro "empaquetado" del objeto en cuestión. Pero solo será beneficioso si está utilizando este tipo de arquitectura de todos modos.

 2
Author: Kitalda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-24 07:42:04

De lejos, la forma más fácil en MI humilde opinión de agrupar objetos. Simplemente agregue una etiqueta de anotación encima del objeto que desea hacer parcelable.

Un ejemplo de la biblioteca está debajo de https://github.com/johncarl81/parceler

@Parcel
public class Example {
    String name;
    int age;

    public Example(){ /*Required empty bean constructor*/ }

    public Example(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public String getName() { return name; }

    public int getAge() { return age; }
}
 2
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-07 21:42:09

Primero implementa Parcelable en tu clase. Luego pase el objeto así.

SendActivity.java

ObjectA obj = new ObjectA();

// Set values etc.

Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);

startActivity(i);

ReceiveActivity.java

Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");

La cadena del paquete no es necesaria, solo la cadena debe ser la misma en ambas Actividades

REFERENCIA

 2
Author: Arpit Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-08 07:30:06

Iniciar otra actividad desde esta actividad pasar parámetros a través del Objeto Bundle

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
startActivity(intent);

Recuperar en otra actividad (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

Esto está bien para el tipo de datos tipo simple. Pero si u quiere pasar datos complejos entre la actividad u necesita serializarlo primero.

Aquí tenemos el Modelo de Empleado

class Employee{
    private String empId;
    private int age;
    print Double salary;

    getters...
    setters...
}

Puede utilizar Gson lib proporcionada por Google para serializar los datos complejos así

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);
 2
Author: user1101821,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-12 21:00:09

Si no es muy exigente con el uso de la función putExtra y solo desea iniciar otra actividad con objetos, puede consultar el GNLauncher ( https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher ) biblioteca que escribí en un intento de hacer este proceso más sencillo.

GNLauncher hace que enviar objetos/datos a una Actividad desde otra Actividad, etc., sea tan fácil como llamar a una función en la Actividad con los datos requeridos como parámetros. Introduce escriba seguridad y elimina todas las molestias de tener que serializar, adjuntando a la intent usando teclas de cadena y deshaciendo la misma en el otro extremo.

 1
Author: jinais,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-02 15:29:19

Clase POJO "Post " (Tenga en cuenta que se implementa Serializable)

package com.example.booklib;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;

public class Post implements Serializable{
    public String message;
    public String bitmap;
    List<Comment> commentList = new ArrayList<Comment>();
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getBitmap() {
        return bitmap;
    }
    public void setBitmap(String bitmap) {
        this.bitmap = bitmap;
    }
    public List<Comment> getCommentList() {
        return commentList;
    }
    public void setCommentList(List<Comment> commentList) {
        this.commentList = commentList;
    }

}

Clase POJO "Comment" (Dado que es miembro de la clase Post,también es necesario implementar el Serializable)

    package com.example.booklib;

    import java.io.Serializable;

    public class Comment implements Serializable{
        public String message;
        public String fromName;
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
        public String getFromName() {
            return fromName;
        }
        public void setFromName(String fromName) {
            this.fromName = fromName;
        }

    }

Luego, en su clase de actividad, puede hacer lo siguiente para pasar el objeto a otra actividad.

ListView listview = (ListView) findViewById(R.id.post_list);
listview.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Post item = (Post)parent.getItemAtPosition(position);
            Intent intent = new Intent(MainActivity.this,CommentsActivity.class);
            intent.putExtra("post",item);
            startActivity(intent);

        }
    });

En su clase de destinatario "CommentsActivity" puede obtener los datos de la siguiente manera

Post post =(Post)getIntent().getSerializableExtra("post");
 0
Author: zawhtut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-21 07:24:18