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

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

Si usted está pasando objetos alrededor, entonces Parcelable fue diseñado para esto. Requiere un poco más de esfuerzo que utilizar la serialización nativa de Java, pero es mucho más rápido (y quiero decir, WAY más rápido).

De los documentos, un ejemplo simple 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 una parcela determinada, debe hacerlo en el mismo orden en que las puso (es decir, en un enfoque FIFO).

Una vez que sus objetos implementan Parcelable es sólo una cuestión de ponerlos en sus intentos con putExtra () :

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

A continuación, puede retirarlos 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 ejecutar una de las siguientes acciones:

 i.putExtra("parcelable_extra", (Parcelable) myParcelableObject); i.putExtra("serializable_extra", (Serializable) myParcelableObject); 

Tendrá que serializar su objeto en algún tipo de representación de cadena. Una representación posible de la secuencia es JSON, y una de las maneras más fáciles de serializar a / de JSON en androide, si usted me pregunta, está con Google GSON .

En ese caso, juse poner el valor de retorno de cadena de (new Gson()).toJson(myObject); Y recuperar el valor de la cadena y el uso de fromJson para convertirlo de nuevo en su objeto.

Sin embargo, si su objeto no es muy complejo, puede que no valga la pena, y podría considerar pasar los valores separados del objeto.

Puede enviar objeto serializable a través de la intención

 // 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 { } 

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

Aquí está lo que Dianne Hackborn (hackbod – un Google Android Software Engineer) tenía que decir sobre el asunto:

Para situaciones en las que sabe que las actividades se ejecutan en el mismo proceso, sólo puede compartir datos a través de globales. Por ejemplo, podría tener un HashMap<String, WeakReference<MyInterpreterState>> global HashMap<String, WeakReference<MyInterpreterState>> y cuando haga un nuevo MyInterpreterState aparecerá con un nombre único para él y lo pondrá en el mapa hash; Para enviar ese estado a otra actividad, simplemente poner el nombre único en el mapa de hash y cuando se inicia la segunda actividad puede recuperar el MyInterpreterState del mapa hash con el nombre que recibe.

Su clase debe implementar Serializable o Parcelable.

 public class MY_CLASS implements Serializable 

Una vez hecho usted puede enviar un objeto en putExtra

 intent.putExtra("KEY", MY_CLASS_instance); startActivity(intent); 

Para obtener extras solo tienes que hacer

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

Si su clase implementa el uso Parcelable a continuación

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

Espero que ayude: D

Si su clase de objeto implementa Serializable , no necesita hacer nada más, puede pasar un objeto serializable.
Eso es lo que uso.

Puedes usar android BUNDLE para hacer esto.

Cree un paquete de su clase como:

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

Luego pase este paquete con INTENT. Ahora puede recrear el objeto de clase pasando el paquete como

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

Declare esto en su clase Custom y utilice.

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 que depende de usted.

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 – http://www.vogella.com/articles/AndroidSQLite/article.html

B. Preferencias compartidas

Supongamos que desea almacenar su nombre de usuario. Así que ahora habrá dos cosa 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 (), 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 la red o puede utilizarlo para su propósito también.

Utilice los habas de java y almacene en él como uno de sus campos y utilice 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 el objeto Serialzation para serializar este objeto y en su otra clase deserializar 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 ha sido escrito en un archivo, se puede leer del archivo y deserializado es decir, la información de tipo y los bytes que representan el objeto y sus datos se pueden utilizar 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. CommonUtilities

Usted puede hacer una clase por su auto que puede contener los 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 los intentos

Consulte este tutorial para ver 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/

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

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

Implementar serializable en tu 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; } } 

A continuación, puede pasar este objeto en intención

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

Int la segunda actividad se pueden obtener datos como este

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

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

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

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

En tu primera Actividad:

 intent.putExtra("myTag", yourObject); 

Y en su segundo:

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

No olvide hacer su objeto personalizado Serializable:

 public class myCustomObject implements Serializable { ... } 

Otra forma de hacerlo es utilizar el objeto Application (android.app.Application). Usted define esto en su archivo AndroidManifest.xml como:

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

A continuación, puede llamar a esto desde cualquier actividad y guardar el objeto en la clase Application .

En la FirstActivity:

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

En SecondActivity, haga lo siguiente:

 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 utilizarse en toda la aplicación. El método Parcelable es aún mejor si desea control explícito sobre el ámbito del objeto o si el ámbito está limitado.

Esto evita el uso de Intents conjunto, sin embargo. No sé si te queda bien. Otra manera que usé esto es tener int identificadores de objetos enviar a través de intents y recuperar objetos que tengo en Maps en el objeto Application .

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

Recuperación de los datos:

 Bundle bundle = getIntent().getExtras(); dataList2 = getIntent().getExtras().getParcelableArrayList("data"); 

Yo uso Gson con su api tan poderosa 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; // 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 se agregan 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 cada proyecto que hago y no tengo problemas de rendimiento.

En su modelo de clase (objeto) implementar Serializable, por 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 tu 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!!

Puede utilizar los métodos putExtra (Serializable ..) y getSerializableExtra () para pasar y recuperar objetos de su tipo de clase; Usted tendrá que marcar su clase Serializable y asegurarse de que todas sus variables miembro son serializable también …

Crear una aplicación para Android

Archivo >> Nuevo >> Aplicación para Android

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

Pakcage: com.hmkcode.android

Mantenga otras selecciones defualt, vaya Siguiente hasta llegar Finalizar

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 la interfaz Serializable.

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> 

Activity_another.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) ActivityMain.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) OtroActividad.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()); } } 
 Intent i = new Intent(); i.putExtra("name_of_extra", myParcelableObject); startACtivity(i); 

Si usted tiene una clase singleton (fx Service) que actúa como puerta de enlace a su capa de modelo de todos modos, puede ser resuelto por tener una variable en esa clase con getters y setters para él.

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 sólo será beneficioso si está utilizando este tipo de arquitectura de todos modos.

De lejos, la forma más fácil de IMHO para los objetos de parcela. Acaba de añadir una etiqueta de anotación sobre el 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; } } 

Sé que esto es tarde, pero es muy simple.Todo lo que tienes que hacer es dejar que tu clase implementar Serializable como

 public class MyClass implements Serializable{ } 

Entonces usted puede pasar a una intención como

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

Para conseguirlo usted simpley llame

 MyClass objec=(MyClass)intent.getExtra("theString"); 

Usando la biblioteca Gson de google se puede pasar el objeto a otra activities.Actually vamos a convertir objeto en forma de cadena json y después de pasar a otra actividad vamos a volver a convertir a 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); 

For reading we need to do the reverse operation in 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); 

Add this dependancy in gradle

 compile 'com.google.code.gson:gson:2.6.2' 

First implement Parcelable in your class. Then pass object like this.

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

The package string isn't necessary, just the string needs to be the same in both Activities

REFERENCE

Short answer for fast need

1. Implement your Class to implements Serializable.

If you have any inner Classes or List<SportsData> dataList; don't forget to implement that class to Serializable too!!

 public class Sports implements Serializable 

2. Put your object to Intent

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

3. And receive take your object in the other Activity Class

 Intent intent = getIntent(); Sports cust = (Sports) intent.getSerializableExtra("sport"); 

the most easiest solution i found is.. to create a class with static data members with getters setters.

set from one activity and get from another activity that object.

activity A

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

activity b

 mytestclass obj= mytestclass.staticfunctionGet(); 

The simplest would be to just use the following where the item is a string:

 intent.putextra("selected_item",item) 

For receiving:

 String name = data.getStringExtra("selected_item"); 

If you are not very particular about using the putExtra feature and just want to launch another activity with objects, you can check out the GNLauncher ( https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher ) library I wrote in an attempt to make this process more straight forward.

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

POJO class "Post " (Note that it is implemented 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; } } 

POJO class "Comment" (Since being a member of Post class,it is also needed to implement the 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; } } 

Then in your activity class, you can do as following to pass the object to another activity.

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

In your recipient class "CommentsActivity" you can get the data as the following

 Post post =(Post)getIntent().getSerializableExtra("post"); 

Start another activity from this activity pass parameters via Bundle Object

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

Retrieve on another activity (YourActivity)

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

This is ok for simple kind 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); 
  • Tomar fotos y geotag
  • Cómo compartir imágenes en google Plus a través de una aplicación para Android?
  • Cómo crear un widget de pantalla de bloqueo personalizado (sólo quiero mostrar un botón)
  • ¿Cuál es el propósito de usar Intent.createChooser () en StartActivity () al enviar correo electrónico en Android
  • Cómo probar Google App Invites
  • Enumera todos los archivos y carpetas de la carpeta dropbox con la API de la bandeja de descarga y el archivo de descarga que se hace clic en android.
  • Usar putExtra para pasar valores al servicio de intenciones
  • Actividad de superusuario no encontrada
  • Cómo agregar un título a un video al compartir un video a través de WhatsApp mediante Intent
  • Android: Evento ACTION_POWER_CONNECTED no se envía a mi BroadcastReceiver
  • Cuando los incendios de Android ACTION_BATTERY_LOW
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.