Cómo pasar un objeto de una actividad a otra en Android

Estoy tratando de trabajar en el envío de un objeto de mi clase de cliente de una Activity y mostrarlo en otra Activity .

El código para la clase de cliente:

 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; } } 

Quiero enviar su objeto de una Activity a otra y luego mostrar los datos de la otra Activity .

¿Cómo puedo lograrlo?

Una opción podría ser permitir que su clase personalizada implemente la interfaz Serializable y, a continuación, puede pasar instancias de objeto en el intento extra mediante la putExtra(Serializable..) del método Intent#putExtra() .

Pseudocódigo :

 //To pass: intent.putExtra("MyClass", obj); // To retrieve object in second Activity getIntent().getSerializableExtra("MyClass"); 

Implemente su clase con Serializable. Supongamos que esta es su clase de entidad:

 import java.io.Serializable; @SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings public class Deneme implements Serializable { public Deneme(double id, String name) { this.id = id; this.name = name; } public double getId() { return id; } public void setId(double id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } private double id; private String name; } 

Estamos enviando el objeto llamado dene de la actividad X a la actividad Y. En alguna parte en la actividad de X;

 Deneme dene = new Deneme(4,"Mustafa"); Intent i = new Intent(this, Y.class); i.putExtra("sampleObject", dene); startActivity(i); 

En la actividad Y estamos consiguiendo el objeto.

 Intent i = getIntent(); Deneme dene = (Deneme)i.getSerializableExtra("sampleObject"); 

Eso es.

El uso de variables estáticas globales no es una buena práctica de ingeniería de software . Convertir los campos de un objeto en tipos de datos primitivos puede ser un trabajo agitado . El uso de serializable está bien, pero no es eficaz en cuanto a rendimiento en la plataforma Android. Parcelable está específicamente diseñado para Android y debe utilizarlo. A continuación se muestra un ejemplo sencillo: Pasar objetos personalizados entre las actividades de Android

Puede generar código Parcelable para su clase utilizando este sitio .

Al llamar a una actividad

 Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj); 

En toClass.java recibe la actividad por

 Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj"); 

Por favor, asegúrese de que la clase de cliente implementa parcelable

 public class Customer implements Parcelable { private String firstName, lastName, address; int age; /* all your getter and setter methods */ public Customer(Parcel in ) { readFromParcel( in ); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public LeadData createFromParcel(Parcel in ) { return new Customer( in ); } public Customer[] newArray(int size) { return new Customer[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(firstName); dest.writeString(lastName); dest.writeString(address); dest.writeInt(age); } private void readFromParcel(Parcel in ) { firstName = in .readString(); lastName = in .readString(); address = in .readString(); age = in .readInt(); } 

En mi experiencia hay tres soluciones principales, cada una con sus desventajas y ventajas:

  1. Implementación de Parcelable

  2. Implementación Serializable

  3. Usando una biblioteca ligera de bus de eventos de algún tipo (por ejemplo, el EventBus de Greenrobot o el Otto de Square)

Parcelable – rápido y estándar de Android, pero tiene un montón de código de boilerplate y requiere cadenas de código duro para referencia cuando tira de valores de la intención (no fuertemente mecanografiado).

Serializable – cerca de cero boilerplate, pero es el enfoque más lento y también requiere hard-coded strings cuando tira valores fuera de la intención (no fuertemente mecanografiado).

Event Bus – cero boilerplate, el enfoque más rápido, y no requiere cadenas codificadas, pero sí requiere una dependencia adicional (aunque generalmente ligero, ~ 40 KB)

He publicado una comparación muy detallada en torno a estos tres enfoques, incluidos los benchmarks de eficiencia. Si estás interesado, puedes encontrarlo en Passing Objects Between Android Activities .

Utilice gson para convertir su objeto a JSON y pasarlo a través de la intención. En la nueva Actividad, convierta el JSON en un objeto.

Ejemplo:

 Gson gson = new Gson(); String myJson = gson.toJson(vp); intent.putExtra("myjson", myjson); 

Y en su próxima actividad, donde desea pasar objeto:

 Gson gson = new Gson(); YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class); 

También puede escribir los datos del objeto en Strings temporales e ints y pasarlos a la actividad. Por supuesto de esa manera, usted consigue los datos transportados, pero no el objeto sí mismo.

Pero si sólo desea mostrarlos, y no utilizar el objeto en otro método o algo así, debería ser suficiente. Lo hice de la misma manera sólo para mostrar datos de un objeto en otra actividad.

 String fName_temp = yourObject.getFname(); String lName_temp = yourObject.getLname(); String age_temp = yourObject.getAge(); String address_temp = yourObject.getAddress(); Intent i = new Intent(this, ToClass.class); i.putExtra("fname", fName_temp); i.putExtra("lname", lName_temp); i.putExtra("age", age_temp); i.putExtra("address", address_temp); startActivity(i); 

También podría pasar directamente en vez de las temp ivars, pero de esta manera es más claro, en mi opinión. Además, puede configurar las estaciones de trabajo a null para que el GarbageCollector las limpie antes.

¡Buena suerte!

En una nota lateral: anule toString () en lugar de escribir su propio método de impresión.

Como se menciona en los comentarios a continuación, así es como obtendrá sus datos en otra actividad:

 String fName = getIntent().getExtras().getInt("fname"); 

Existen varias maneras de acceder a variables u objetos en otras clases o Actividad.

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. Depende de ti.

E. Pasar datos a través de Intents y Parcelable Interface.

Depende de las necesidades de su proyecto.

A. Base de datos

SQLite es una base de datos de código abierto que está incrustada en Android. SQLite soporta funciones de base de datos relacional estándar como sintaxis SQL, transacciones y sentencias preparadas.

Tutoriales

B. Preferencias compartidas

Supongamos que desea almacenar su nombre de usuario. Así que ahora habrá dos cosas, un nombre de usuario clave , valor de valor.

Cómo almacenar

  // 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 () y putLong () puede guardar su dtatype deseado.

Como buscar

 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

Serialización de objetos se utiliza si queremos guardar un estado de objeto para enviarlo a través de una red o puede utilizarlo también para su propósito.

Utilizar Java beans y almacenar en él como uno de sus campos y utilizar getters y setter para eso.

JavaBeans son clases Java que tienen propiedades. Piense en las propiedades como variables de instancia privadas. Dado que son privados, la única forma en que se les puede acceder desde fuera de su clase es a través de métodos en la clase. Los métodos que cambian el valor de una propiedad se denominan 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 utilizando

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

A continuación, utilice serialización de objeto para serializar este objeto y en su otra clase deserialice este objeto.

En la serialización un objeto puede representarse 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 haya escrito en un archivo, puede ser leído del archivo y deserializado. Es decir, la información de tipo y los bytes que representan el objeto y sus datos pueden usarse para recrear el objeto en la memoria.

Si desea tutorial para esto, consulte:

  • Serialización en Java (blog)

  • Obtener variable en otras clases (Desbordamiento de pila)

D. CommonUtilities

Usted puede hacer una clase por sí mismo que puede contener datos comunes que usted necesita con frecuencia en su proyecto.

Muestra

 public class CommonUtilities { public static String className = "CommonUtilities"; } 

E. Pasar datos a través de las intenciones

Por favor, consulte el tutorial Android – Parcel datos para pasar entre las actividades que utilizan las clases Parcelable para esta opción de pasar los datos.

Hice una clase auxiliar singleton que contiene objetos temporales.

 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; } } 

En lugar de poner tus objetos dentro de Intent, usa IntentHelper:

 IntentHelper.addObjectForKey(obj, "key"); 

Dentro de su nueva Actividad, puede obtener el objeto:

 Object obj = (Object) IntentHelper.getObjectForKey("key"); 

Tenga en cuenta que una vez cargado, el objeto se elimina para evitar referencias innecesarias.

He encontrado un método simple y elegante:

  • NO Parcelable
  • NO Serializable
  • NO Campo estático
  • No hay autobús de eventos

Método 1

Código de la primera actividad:

  final Object objSent = new Object(); final Bundle bundle = new Bundle(); bundle.putBinder("object_value", new ObjectWrapperForBinder(objSent)); startActivity(new Intent(this, SecondActivity.class).putExtras(bundle)); Log.d(TAG, "original object=" + objSent); 

Código para la segunda actividad:

  final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value")).getData(); Log.d(TAG, "received object=" + objReceived); 

Usted encontrará objSent y objReceived tienen el mismo hashCode , por lo que son idénticos.

¿Pero por qué podemos pasar un objeto java de esta manera?

En realidad, el fichero android creará una referencia JNI global para el objeto java y lanzará esta referencia JNI global cuando no haya referencia para este objeto java. Binder guardará esta referencia JNI global en el objeto Binder.

* PRECAUCIÓN: este método SOLAMENTE funciona a menos que las dos actividades se ejecuten en el mismo proceso, de lo contrario lanzar ClassCastException en (ObjectWrapperForBinder) getIntent (). GetExtras (). GetBinder ("object_value") *

Class ObjectWrapperForBinder definición

 public class ObjectWrapperForBinder extends Binder { private final Object mData; public ObjectWrapperForBinder(Object data) { mData = data; } public Object getData() { return mData; } } 

Método 2

  • Para el remitente,
    1. Use método nativo personalizado para agregar su objeto java a la tabla de referencia global JNI (a través de JNIEnv :: NewGlobalRef)
    2. Poner el retorno entero (en realidad, JNIEnv :: NewGlobalRef return jobject, que es un puntero, podemos lanzarlo a int de forma segura) a su Intención (vía Intent :: putExtra)
  • Para el receptor
    1. Obtener entero de Intent (a través de Intent :: getInt)
    2. Use método nativo personalizado para restaurar su objeto java desde la tabla de referencia global de JNI (a través de JNIEnv :: NewLocalRef)
    3. Eliminar el elemento de la tabla de referencia global JNI (a través de JNIEnv :: DeleteGlobalRef),

Pero el método 2 tiene un problema poco pero serio, si el receptor falla al restaurar el objeto java (por ejemplo, alguna excepción sucede antes de restaurar el objeto java, o la actividad del receptor no existe en absoluto), entonces el objeto java se convertirá en un Huérfano o pérdida de memoria, el método 1 no tiene este problema, ya que el procesador android controlará esta excepción

Método 3

Para invocar el objeto java de forma remota, vamos a crear un contrato de datos / interfaz para describir el objeto java, vamos a utilizar el archivo aidl

IDataContract.aidl

 package com.example.objectwrapper; interface IDataContract { int func1(String arg1); int func2(String arg1); } 

Código para la primera actividad

  final IDataContract objSent = new IDataContract.Stub() { @Override public int func2(String arg1) throws RemoteException { // TODO Auto-generated method stub Log.d(TAG, "func2:: arg1=" + arg1); return 102; } @Override public int func1(String arg1) throws RemoteException { // TODO Auto-generated method stub Log.d(TAG, "func1:: arg1=" + arg1); return 101; } }; final Bundle bundle = new Bundle(); bundle.putBinder("object_value", objSent.asBinder()); startActivity(new Intent(this, SecondActivity.class).putExtras(bundle)); Log.d(TAG, "original object=" + objSent); 

Código para la segunda actividad:

Cambie el atributo android: process en AndroidManifest.xml a un nombre de proceso no vacío para asegurarse de que la segunda actividad se ejecute en otro proceso

  final IDataContract objReceived = IDataContract.Stub.asInterface(getIntent().getExtras().getBinder("object_value")); try { Log.d(TAG, "received object=" + objReceived + ", func1()=" + objReceived.func1("test1") + ", func2()=" + objReceived.func2("test2")); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

De esta manera, podemos pasar una interfaz entre dos actividades a pesar de que se ejecutan en diferentes procesos, y llamar al método de interfaz de forma remota

Método 4

El método 3 no parece bastante simple porque debemos implementar una interfaz de ayuda. Si solo quieres hacer tarea sencilla y el valor de retorno del método es innecesario, podemos usar android.os.Messenger

Código de la primera actividad (remitente):

 public class MainActivity extends Activity { private static final String TAG = "MainActivity"; public static final int MSG_OP1 = 1; public static final int MSG_OP2 = 2; public static final String EXTRA_MESSENGER = "messenger"; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub Log.e(TAG, "handleMessage:: msg=" + msg); switch (msg.what) { case MSG_OP1: break; case MSG_OP2: break; default: break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startActivity(new Intent(this, SecondActivity.class).putExtra(EXTRA_MESSENGER, new Messenger(mHandler))); } } 

Código para la segunda actividad (receptor):

 public class SecondActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); final Messenger messenger = getIntent().getParcelableExtra(MainActivity.EXTRA_MESSENGER); try { messenger.send(Message.obtain(null, MainActivity.MSG_OP1, 101, 1001, "10001")); messenger.send(Message.obtain(null, MainActivity.MSG_OP2, 102, 1002, "10002")); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

Todo el Messenger.send se ejecutará en un controlador de forma asincrónica y secuencial.

En realidad, android.os.Messenger es también una interfaz de ayuda, si usted tiene el código fuente de Android, puede encontrar un archivo llamado IMessenger.aidl

 package android.os; import android.os.Message; /** @hide */ oneway interface IMessenger { void send(in Message msg); } 

La mejor manera es tener una clase (llamada Control) en su aplicación que contenga una variable estática del tipo 'Cliente' (en su caso). Inicialice la variable en su Actividad A.

Por ejemplo:

 Control.Customer = CustomerClass; 

A continuación, vaya a la Actividad B y búsquelo desde la clase Control. No olvide asignar un nulo después de usar la variable, de lo contrario la memoria se perderá.

 public class MyClass implements Serializable{ Here is your instance variable } 

Ahora desea pasar el objeto de esta clase en startActivity. Simplemente use esto:

 Bundle b = new Bundle(); b.putSerializable("name", myClassObject); intent.putExtras(b); 

Esto funciona aquí porque MyClass implementa Serializable .

Cree su propia clase Customer como sigue:

 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; } } 

En su método onCrate()

 @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); } 

En la clase de xyz activity , debes usar el siguiente código:

 Intent intent=getIntent(); Customer cust=(Customer)intent.getSerializableExtra("bundle"); textViewName.setText(cust.getName()); textViewCity.setText(cust.getCity()); 

Si elige usar la forma descrita por Samuh, recuerde que sólo se pueden enviar valores primitivos. Es decir, los valores que son parcable. Por lo tanto, si su objeto contiene objetos complejos estos no seguirán. Por ejemplo, las variables como Bitmap, HashMap etc … Estos son difíciles de pasar por la intención.

En general, te aconsejo enviar sólo tipos de datos primitivos como extras, como String, int, boolean etc. En tu caso sería: String fname , String lname , int age y String address .

Mi opinión: Los objetos más complejos se comparten mejor mediante la implementación de un ContentProvider , SDCard , etc. También es posible usar una variable estática , pero esto puede conducir rápidamente a un código propenso a errores …

Pero de nuevo, es sólo mi opinión subjetiva.

Estoy utilizando parcelable para enviar datos de una actividad a otra acivity. Aquí está mi código que funciona bien en mi proyecto.

 public class Channel implements Serializable, Parcelable { /** */ private static final long serialVersionUID = 4861597073026532544L; private String cid; private String uniqueID; private String name; private String logo; private String thumb; /** * @return The cid */ public String getCid() { return cid; } /** * @param cid * The cid to set */ public void setCid(String cid) { this.cid = cid; } /** * @return The uniqueID */ public String getUniqueID() { return uniqueID; } /** * @param uniqueID * The uniqueID to set */ public void setUniqueID(String uniqueID) { this.uniqueID = uniqueID; } /** * @return The name */ public String getName() { return name; } /** * @param name * The name to set */ public void setName(String name) { this.name = name; } /** * @return the logo */ public String getLogo() { return logo; } /** * @param logo * The logo to set */ public void setLogo(String logo) { this.logo = logo; } /** * @return the thumb */ public String getThumb() { return thumb; } /** * @param thumb * The thumb to set */ public void setThumb(String thumb) { this.thumb = thumb; } public Channel(Parcel in) { super(); readFromParcel(in); } public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() { public Channel createFromParcel(Parcel in) { return new Channel(in); } public Channel[] newArray(int size) { return new Channel[size]; } }; public void readFromParcel(Parcel in) { String[] result = new String[5]; in.readStringArray(result); this.cid = result[0]; this.uniqueID = result[1]; this.name = result[2]; this.logo = result[3]; this.thumb = result[4]; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(new String[] { this.cid, this.uniqueID, this.name, this.logo, this.thumb}); } } 

En activityA usarlo así:

 Bundle bundle = new Bundle(); bundle.putParcelableArrayList("channel",(ArrayList<Channel>) channels); Intent intent = new Intent(ActivityA.this,ActivityB.class); intent.putExtras(bundle); startActivity(intent); 

En ActivityB utilícelo de esta manera para obtener datos:

 Bundle getBundle = this.getIntent().getExtras(); List<Channel> channelsList = getBundle.getParcelableArrayList("channel"); 

Puedes intentar usar esa clase. La limitación es que no se puede usar fuera de un proceso.

Una actividad:

  final Object obj1 = new Object(); final Intent in = new Intent(); in.putExtra(EXTRA_TEST, new Sharable(obj1)); 

Otra actividad:

 final Sharable s = in.getExtras().getParcelable(EXTRA_TEST); final Object obj2 = s.obj(); public final class Sharable implements Parcelable { private Object mObject; public static final Parcelable.Creator < Sharable > CREATOR = new Parcelable.Creator < Sharable > () { public Sharable createFromParcel(Parcel in ) { return new Sharable( in ); } @Override public Sharable[] newArray(int size) { return new Sharable[size]; } }; public Sharable(final Object obj) { mObject = obj; } public Sharable(Parcel in ) { readFromParcel( in ); } Object obj() { return mObject; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel out, int flags) { final long val = SystemClock.elapsedRealtime(); out.writeLong(val); put(val, mObject); } private void readFromParcel(final Parcel in ) { final long val = in .readLong(); mObject = get(val); } ///// private static final HashMap < Long, Object > sSharableMap = new HashMap < Long, Object > (3); synchronized private static void put(long key, final Object obj) { sSharableMap.put(key, obj); } synchronized private static Object get(long key) { return sSharableMap.remove(key); } } 

Crete una clase como clase bean e implementa la interfaz Serializable . Entonces podemos pasarlo por el método de intent , por ejemplo:

 intent.putExtra("class", BeanClass); 

A continuación, obtener de la otra actividad, por ejemplo:

 BeanClass cb = intent.getSerializableExtra("class"); 

Crear dos métodos en su clase personalizada como este

 public class Qabir { private int age; private String name; Qabir(){ } Qabir(int age,String name){ this.age=age; this.name=name; } // method for sending object public String toJSON(){ return "{age:" + age + ",name:\"" +name +"\"}"; } // method for get back original object public void initilizeWithJSONString(String jsonString){ JSONObject json; try { json =new JSONObject(jsonString ); age=json.getInt("age"); name=json.getString("name"); } catch (JSONException e) { e.printStackTrace(); } } } 

Now in your sender Activity do like this

 Qabir q= new Qabir(22,"KQ"); Intent in=new Intent(this,SubActivity.class); in.putExtra("obj", q.toJSON()); startActivity( in); 

And in your receiver Activity

 Qabir q =new Qabir(); q.initilizeWithJSONString(getIntent().getStringExtra("obj")); 

This question is also discussed in another Stack Overflow question. Please have a look at a solution to Passing data through intent using Serializable . The main point is about using Bundle object which stores the necessary data inside Intent .

  Bundle bundle = new Bundle(); bundle.putSerializable(key1, value1); bundle.putSerializable(key2, value2); bundle.putSerializable(key3, value3); intent.putExtras(bundle); 

To extract values:

  Bundle bundle = new Bundle(); for (String key : bundle.keySet()) { value = bundle.getSerializable(key)); } 

Yeah, using a static object is by far the easiest way of doing this with custom non-serialisable objects.

Android Activity objects can be destroyed and reconstituted. So, you will need to use another approach to look them – or any object they create !!! – up. That is, you could pass as static class reference but then the object handle (Java calls these "references", as does SmallTalk; but they are not references in the sense of C or assembly) will be possibly invalid later because a "feature" of Android OE is any Activity can be annihilated and reconstituted later.

The original question asked "How to pass object from one activity to another in Android" and nobody has answered that. For sure, you can serialized (Serializable, Parcelable, to/from JSON) and pass a copy of the object's data and a new object having the same data could be created; but it will NOT have the same references/handles. Also, many others mentioned you can store the reference in a static store. And that will work unless Android decides to onDestroy your Activity.

So, to really solve the original question you would need a static lookup plus each object will update its reference when/if it is recreated. Eg each Android Activity would relist itself if its onCreate is called. You can also see how some people use the task list to search out an Activity by name. (system is temporarily destroying this instance of the activity to save space..getRunningTasks, the task list is effectively a specialized listing of the most recent object instance of each Activity).

Para referencia:

Stopped: "The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity object is retained in memory , it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere."

onDestroy "system is temporarily destroying this instance of the activity to save space."

So, the Message Bus is a workable solution. It basically "punts". Rather than try to have references to objects; then you re-architect your design to use MessagePassing instead of SequentialCode. Exponentially harder to debug; but it lets you ignore these sort of OperatingEnvironment understandings. Effectively, each object method access is inverted so the caller posts a Message and the object itself defines a handler for that message. Lots more code but can make it robust with the Android OE restrictions.

If all you want is the top Activity (typical thing in Android apps due to "Context" being needed everywhere), then you can just have each Activity lists itself as "top" in the static global space whenever its onResume is called. Then your AlertDialog or whatever which needs a context can just grab it from there. Also, its a bit yucky to use a global but can simplifying passing a Context up and down everywhere and, for sure, when you use a MessageBus then IT IS global anyways.

  1. I know that static is bad, but it seems that we're forced to use it here. The problem with parceables/seriazables is that the two activities have duplicate instances of the same object = waste of memory and CPU.

     public class IntentMailBox { static Queue<Object> content = new LinkedList<Object>(); } 

Calling activity

 IntentMailBox.content.add(level); Intent intent = new Intent(LevelsActivity.this, LevelActivity.class); startActivity(intent); 

Called activity (note that onCreate() and onResume() may be called multiple times when the system destroys and recreates activities)

 if (IntentMailBox.content.size()>0) level = (Level) IntentMailBox.content.poll(); else // Here you reload what you have saved in onPause() 
  1. Another way is to declare a static field of the class that you want to pass in that very class. It will serve only for this purpose. Don't forget that it can be null in onCreate, because your app package has been unloaded from memory by system and reloaded later.

  2. Bearing in mind that you still need to handle activity lifecycle, you may want to write all the data straight to shared preferences, painful with complex data structures as it is.

Start another activity from this activity and pass parameters via Bundle Object

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

Retrive data on another activity (YourActivity)

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

This is ok for simple kind of data type. But if u want to pass complex data in between activity. U need to serialize it first.

Here we have Employee Model

 class Employee{ private String empId; private int age; print Double salary; getters... setters... } 

You can use Gson lib provided by google to serialize the complex data like this

 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); 

I had always wondered why this can't be as simple as calling into a method of the other activity. I recently wrote a utility library that makes it almost as simple as that. You can check it out here( https://github.com/noxiouswinter/gnlib_android/wiki/gnlauncher ).

GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in tha Activity with the required data as parameters. It introduces type safety and removes all the hastles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.

Uso

Define an interface with the methods you want to call on the Activity to launch.

 public interface IPayload { public void sayHello(String name, int age); } 

Implement the above interface on the Activity to launch into. Also notify GNLauncher when the activity is ready.

 public class Activity_1 extends Activity implements IPayload { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Notify GNLauncher when the Activity is ready. GNLauncher.get().ping(this); } @Override public void sayHello(String name, int age) { Log.d("gnlib_test", "Hello " + name + "! \nYour age is: " + age); } } 

In the other Activity, get a proxy to the above Activity and call any method with the desired parameters.

 public class Activity_2 extends Activity { public void onClick(View v) { ((IPayload)GNLauncher.get().getProxy(this, IPayload.class, Activity_1.class)).sayHello(name, age); } } 

The first activity will be launched and the method called into with the required parameters.

Requisitos previos

Please refer to https://github.com/noxiouswinter/gnlib_android/wiki#prerequisites for information on how to add the dependencies.

Pass object from one activity to another activity.

(1) source activity

 Intent ii = new Intent(examreport_select.this, BarChartActivity.class); ii.putExtra("IntentExamResultDetail", (Serializable) your List<ArraList<String>> object here); startActivity(ii); 

(2) destination acitivity

 List<ArrayList<String>> aa = (List<ArrayList<String>>) getIntent() .getSerializableExtra("IntentExamResultDetail"); 

I used to set object with Pacelable or Serializable to transfer, but whenever I add other variables to object(model), I have to register it all. It's so nconvenient.

It's super easy to transfer object between activities or fragments.

Android DataCache

We can pass the object from one activity to another activity:

 SupplierDetails poSuppliersDetails = new SupplierDetails(); 

Inside poSuppliersDetails we have some values. Now I am sending this object to target activity:

 Intent iPODetails = new Intent(ActivityOne.this, ActivityTwo.class); iPODetails.putExtra("poSuppliersDetails", poSuppliersDetails); 

How to get this in ACtivityTwo:

 private SupplierDetails supplierDetails; supplierDetails =(SupplierDetails) getIntent().getSerializableExtra("poSuppliersDetails"); 

Above answers almost all correct but for those who doesn't undestand those answers Android has powerfull class Intent with help of it you share data between not only activity but another components of Android (broadcasr receiver, servises for content provide we use ContetnResolver class no Intent). In your activity you build intent

 Intent intent = new Intent(context,SomeActivity.class); intent.putExtra("key",value); startActivity(intent); 

In your receving activity you have

 public class SomeActivity extends AppCompactActivity { public void onCreate(...){ ... SomeObject someObject = getIntent().getExtras().getParceable("key"); } } 

You have to implement Parceable or Serializable interface on your object in order to share between activities. It is hard to implement Parcealbe rather than Serializable interface on object that's why android has plugin especially for this.Download it and use it

Pass one activity to another:

 startActivity(new Intent(getBaseContext(),GetActivity.class).putExtra("passingkey","passingvalue")); 

Get values:

 String myvalue= getIntent().getExtras("passingkey"); 

Hello all I see a lot of good options but I was wondering why Binding hasn't been used?

Passing a reference to an object just seems more efficient to me than serializing and desterilizing objects, but I have not done a deep dive to see if that is what is going on behind the scenes.

Creating a Binder is simple enough…

 public class MyBinder extends Binder { private Object myObject; public MyBinder(Object object) { myObject = object; } public Object getObject() { return myObject; } } 

And creating the parcelable to use it isn't that bad ether.

 public class MyParcelable implements Parcelable { private Object myObject; public MyParcelable() { } public MyParcelable(Parcel parcel) { myObject = ((MyBinder)parcel.readStrongBinder()).getObject(); } public void setObject(Object object) { myObject = object; } public Object getObject() { return myObject; } public void writeToParcel(Parcel parcel, int flags) { parcel.writeStrongBinder(new MyBinder(myObject)); } public int describeContents() { return myObject == null ? 0 : 1; } public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() { public MyParcelable createFromParcel(Parcel parcel) { return new MyParcelable(parcel); } public MyParcelable[] newArray(int length) { return new MyParcelable[length]; } }; } 

This logic is really cool because you are actually passing a reference from activity to activity.

I would advise checking for nulls and if the instanceof Binder is MyBinder!

and to implement this you just…

Send it off

 Object myObject = "some object"; MyParcelable myParcelable = new MyParcelable(); myParcelable.setObject(myObject); intent.putExtra("MyParcelable", myParcelable); 

Get it back

 myParcelable = (MyParcelable) getIntent().getExtras().getParcelable("MyParcelable"); myObject = myParcelable.getObject(); 

Heck someone could get all crazy and make this sucker a true generic.

  • Determine si JSON es un JSONObject o JSONArray
  • Programación de Android m antes de los objetos
  • Android: vista de 360 ​​grados de un objeto
  • Obtener valor específico de JSONArray
  • Obtención de base de datos SQLite y almacenamiento en una matriz de objetos
  • ¿Cómo se envía una matriz de objetos personalizados entre actividades?
  • Asignar largo a Long en Java
  • Pon el Objeto como intención para la siguiente actividad
  • Cómo guardar ArrayList personalizado en la rotación de la pantalla de Android?
  • crear un adaptador para rellenar Spinner con objetos
  • Almacenar y recuperar un objeto de clase en preferencia compartida
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.