Parcelable encoder/decoder (External class) - android

I have an external Java library with a lot of common objects (i.e. User with name, surname, address...). The thing that i want to build up is a (de)serializer class that transforms all my objects into Parcelable objects to send with Intents. The problem is that Android's intents don't support putExtra(String,Parcel) or something similar. Have you got an idea on how to overcome this inconvenient?
Actually I'm putting all my instances in the Application class, but I think it's a dirty method...cleaner one?

You can use putExtras(Bundle extras) method of Intent and implement in your class method exportToBundle() which returns Bundle with values of this object. If you don't want to create any other methods in your class you can create another utility class with static method which converts object of your class to Bundle. And if your class is Parcelable you can put it directly to the Bundle using putParcelable(String key, Parcelable value) method.

You can directly put a Parcelable class into the intent so what you're looking for is supported. There is a word of warning here and I think you've already have this concept down by mentioning serialize / de-serialize. You are sending a copy of the class which will be reconstructed by the class processing the intent. The official android example is weak because only one integer is sent and we can do that already.
Example intent passing a class
Intent intent = new Intent(context, TheClassImCalling.class);
// use a constant that's public or an R string so both the sender
// and receiver are working on the same class
// the class you are sending goes into the putExtra method statement.
intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
mKmlSummary);
startActivity(intent);
You pull a copy out of the class out with a statement like this using the same constant you used to send it.
KMLSummary mkmlSummary = intent.getExtras().getParcelable(
ImageTextListViewActivity.EXTRA_KMLSUMMARY);
Here are the methods that have to be implemented
public class KmlSummary implements Parcelable {
// a constructor with Parcel as argument.
// you read and write the values in the same order.
public KmlSummary(Parcel in) {
this._id = in.readInt();
this._description = in.readString();
this._name = in.readString();
this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
in.readDouble());
this._resrawid = in.readInt();
this._resdrawableid = in.readInt();
this._pathstring = in.readString();
String s = in.readString();
this.set_isThumbCreated(Boolean.parseBoolean(s));
}
// Overridden methods for the Parseable interface.
#Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(this._id);
arg0.writeString(this._description);
arg0.writeString(this._name);
arg0.writeDouble(this.get_bounds().southwest.latitude);
arg0.writeDouble(this.get_bounds().southwest.longitude);
arg0.writeDouble(this.get_bounds().northeast.latitude);
arg0.writeDouble(this.get_bounds().northeast.longitude);
arg0.writeInt(this._resrawid);
arg0.writeInt(this._resdrawableid);
arg0.writeString(this.get_pathstring());
String s = Boolean.toString(this.isThumbCreated());
arg0.writeString(s);
}
#Override
public int describeContents() {
//
return 0;
}
// Some glue to tell the OS how to create the class from the parcel
#SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public KmlSummary createFromParcel(Parcel in) {
return new KmlSummary(in);
}
public KmlSummary[] newArray(int size) {
return new KmlSummary[size];
}
};
}
That's it you can serialize the class into an intent and de-serialize the class from the intent.
Good Luck
Danny117

Related

How to pass array or arraylist by intent which has unserializable data?

What I want to do is passing DataModel array between Activity by Intent.
DataModel class has Bitmap object and FirebaseVisionLabel object. I found many sites to implement this.
Many people said that DataModel class should implements Serializable or Parceable interface to pass DataModel[] or ArrayList<DataModel>.
So I tried, but the real problem was FirebaseVisionLabel class cannot be serializable. Also, I cannot modify that class because it is firebase library.
How can I pass DataModel array by intent??
Point
Want to pass array or arraylist of my own class by intent.
that class has unserializable object and I cannot modify.
how can I pass or deal with it?
Use Parceable. It works perfect
public class Test implements Parcelable
{
FirebaseVisionLabel firebaseVisionLabel;
String testString;
protected Test(Parcel in) {
testString = in.readString();
}
public static final Creator<Test> CREATOR = new Creator<Test>() {
#Override
public Test createFromParcel(Parcel in) {
return new Test(in);
}
#Override
public Test[] newArray(int size) {
return new Test[size];
}
};
public FirebaseVisionLabel getFirebaseVisionLabel() {
return firebaseVisionLabel;
}
public void setFirebaseVisionLabel(FirebaseVisionLabel firebaseVisionLabel) {
this.firebaseVisionLabel = firebaseVisionLabel;
}
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(testString);
}
}
After that for passing data through intent
Test test = new Test();
test.setTestString("test");
test.setFirebaseVisionLabel(yourObject);
Intent intent = new Intent(this, BaseActivity.class);
intent.putExtra("key", test);
startActivity(intent);
Use the below code to get ArrayList data without Serialized or Parcelable:
Consider,
Intent intent = new Intent(this, your_second_class.class);
intent.putStringArrayListExtra("<your_name_here>", your_list_here);
startActivity(intent);
Then in your second class use:
Intent i = getIntent();
new_list = i.getStringArrayListExtra("<your_name_here>");
Hope it will work fine.
You may use Application class, which can be used in all the screen, activities.
So store array in Application class and used anywhere in app.
FirebaseVisionLabel doesn't have too many properties. You will need to serialize Label / Confidence /... (anything you care) yourself by creating your own VisionLabelParcelable class.
So far, there are not enough use cases to make ML Kit return a Parcelable FirebaseVisionLabel. Most apps should extract the info they are interested in and pass around if they want.

Parcelable for object [duplicate]

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];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
During my Android course, the instructor used this block of code and they didn't quite explained this. How can I interpret this code? I tried reading the documentation but I failed to interpret.
This concept is called Parcelable
A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.
To allow your custom object to be parsed to another component they need to implement the android.os.Parcelable interface. It must also provide a static final method called CREATOR which must implement the Parcelable.Creator interface.
The code you have written will be your model class.
You can use Parcelable in Activity like :
intent.putExtra("student", new Student("1")); //size which you are storing
And to get this object :
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
Here Student is a model class name. replace this with yours.
In simple terms Parcelable is used to send a whole object of a model class to another page.
In your code this is in the model and it is storing int value size to Parcelable object to send and retrieve in other activity.
Reference :
Tutorial 1
Tutorial 2
Tutorial 3
--> Parcelable in Android
The Bundle object which is used to pass data to Android components is a key/value store for specialized objects. It is similar to a Map but can only contain these specialized objects
You can place the following objects types into a Bundle:
String
primitives
Serializable
Parcelable
If you need to pass your customer objects via a Bundle, you should implement the Parcelable interface.
--> Implementing Parcelable
You can create a POJO class for this, but you need to add some extra code to make it Parcelable. Have a look at the implementation.
public class Student implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Student(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Student(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
#override
public int describeContents(){
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
Once you have created this class, you can easily pass objects of this class through the Intent like this, and recover this object in the target activity.
intent.putExtra("student", new Student("1","Mike","6"));
Here, the student is the key which you would require to unparcel the data from the bundle.
Bundle data = getIntent().getExtras();
Student student = data.getParcelable("student");
This example shows only String types. But, you can parcel any kind of data you want. Try it out.

Pass a model class object from a Fragment to another Activity [duplicate]

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?
If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).
From the docs, a simple example for how to implement is:
// 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 that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).
Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
Then you can pull them back out with getParcelableExtra():
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:
i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);
You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.
In that case you just put the string return value from (new Gson()).toJson(myObject); and retrieve the string value and use fromJson to turn it back into your object.
If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.
You can send serializable object through 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 {
}
For situations where you know you will be passing data within an application, use "globals" (like static Classes)
Here is what Dianne Hackborn (hackbod - a Google Android Software Engineer) had to say on the matter:
For situations where you know the activities are running in the same
process, you can just share data through globals. For example, you
could have a global HashMap<String, WeakReference<MyInterpreterState>>
and when you make a new MyInterpreterState come up with a unique name
for it and put it in the hash map; to send that state to another
activity, simply put the unique name into the hash map and when the
second activity is started it can retrieve the MyInterpreterState from
the hash map with the name it receives.
Your class should implements Serializable or Parcelable.
public class MY_CLASS implements Serializable
Once done you can send an object on putExtra
intent.putExtra("KEY", MY_CLASS_instance);
startActivity(intent);
To get extras you only have to do
Intent intent = getIntent();
MY_CLASS class = (MY_CLASS) intent.getExtras().getSerializable("KEY");
If your class implements Parcelable use next
MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");
I hope it helps :D
implement serializable in your class
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;
}
}
Then you can pass this object in intent
Intent intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity(intent);
int the second activity you can get data like this
Place place= (Place) getIntent().getSerializableExtra("PLACE");
But when the data become large,this method will be slow.
Short answer for fast need
1. Implement your Class to Serializable.
If you have any inner Classes don't forget to implement them to Serializable too!!
public class SportsData implements Serializable
public class Sport implements Serializable
List<Sport> clickedObj;
2. Put your object into Intent
Intent intent = new Intent(SportsAct.this, SportSubAct.class);
intent.putExtra("sport", clickedObj);
startActivity(intent);
3. And receive your object in the other Activity Class
Intent intent = getIntent();
Sport cust = (Sport) intent.getSerializableExtra("sport");
if your object class implements Serializable, you don't need to do anything else, you can pass a serializable object. that's what i use.
There are a couple of ways by which you can access variables or objects in other classes or Activity.
A. Database
B. shared preferences.
C. Object serialization.
D. A class that can hold common data can be named Common Utilities it depends on you.
E. Passing data through Intents and Parcelable Interface.
It depends upon your project needs.
A. Database
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions, and prepared statements.
Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html
B. Shared Preferences
Suppose you want to store username. So there will be now two things a Key Username, Value Value.
How to store
// Create an 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();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
How to fetch
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");
http://developer.android.com/reference/android/content/SharedPreferences.html
C. Object Serialization
Object serialization is used if we want to save an object state to send it over the network or you can use it for your purpose also.
Use java beans and store in it as one of his fields and use getters and setter for that
JavaBeans are Java classes that have properties. Think of
properties as private instance variables. Since they're private, the only way
they can be accessed from outside of their class is through methods in the class. The
methods that change a property's value are called setter methods, and the methods
that retrieve a property's value are called getter methods.
public class VariableStorage implements Serializable {
private String inString ;
public String getInString() {
return inString;
}
public void setInString(String inString) {
this.inString = inString;
}
}
Set the variable in your mail method by using
VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);
Then use object Serialzation to serialize this object and in your other class deserialize this object.
In serialization, an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
If you want a tutorial for this to refer this link
http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html
Get variable in other classes
D. CommonUtilities
You can make a class by your self which can contain common data which you frequently need in your project.
Sample
public class CommonUtilities {
public static String className = "CommonUtilities";
}
E. Passing Data through Intents
Please refer to this tutorial for this option of passing data.
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
You can use android BUNDLE to do this.
Create a Bundle from your class like:
public Bundle toBundle() {
Bundle b = new Bundle();
b.putString("SomeKey", "SomeValue");
return b;
}
Then pass this bundle with INTENT.
Now you can recreate your class object by passing bundle like
public CustomClass(Context _context, Bundle b) {
context = _context;
classMember = b.getString("SomeKey");
}
Declare this in your Custom class and use.
Thanks for parcelable help but i found one more optional solution
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;
}
}
In Activity One
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);
Get Data In Activity 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());
}
I use Gson with its so powerful and simple api to send objects between activities,
Example
// 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 functions you add them to the objects that you want to send
Usage
Send Object From A to 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);
Receive In 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);
}
I use it almost in every project i do and I have no performance issues.
I struggled with the same problem. I solved it by using a static class, storing any data I want in a HashMap. On top I use an extension of the standard Activity class where I have overriden the methods onCreate an onDestroy to do the data transport and data clearing hidden. Some ridiculous settings have to be changed e.g. orientation-handling.
Annotation:
Not providing general objects to be passed to another Activity is pain in the ass. It's like shooting oneself in the knee and hoping to win a 100 metres. "Parcable" is not a sufficient substitute. It makes me laugh... I don't want to implement this interface to my technology-free API, as less I want to introduce a new Layer... How could it be, that we are in mobile programming so far away from modern paradigm...
In your first Activity:
intent.putExtra("myTag", yourObject);
And in your second one:
myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");
Don't forget to make your custom object Serializable:
public class myCustomObject implements Serializable {
...
}
Another way to do this is to use the Application object (android.app.Application). You define this in you AndroidManifest.xml file as:
<application
android:name=".MyApplication"
...
You can then call this from any activity and save the object to the Application class.
In the FirstActivity:
MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);
In the SecondActivity, do :
MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);
This is handy if you have objects that have application level scope i.e. they have to be used throughout the application. The Parcelable method is still better if you want explicit control over the object scope or if the scope is limited.
This avoid the use of Intents altogether, though. I don't know if they suits you. Another way I used this is to have int identifiers of objects send through intents and retrieve objects that I have in Maps in the Application object.
in your class model (Object) implement Serializable, for
Example:
public class MensajesProveedor implements Serializable {
private int idProveedor;
public MensajesProveedor() {
}
public int getIdProveedor() {
return idProveedor;
}
public void setIdProveedor(int idProveedor) {
this.idProveedor = idProveedor;
}
}
and your first Activity
MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("mensajes",mp);
startActivity(i);
and your second Activity (NewActivity)
MensajesProveedor mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");
good luck!!
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];
}
};
}
Passing the data:
Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
intent.putExtras(bundle);
startActivity(intent);
Retrieving the data:
Bundle bundle = getIntent().getExtras();
dataList2 = getIntent().getExtras().getParcelableArrayList("data");
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();
Using google's Gson library you can pass object to another activities.Actually we will convert object in the form of json string and after passing to other activity we will again re-convert to object like this
Consider a bean class like this
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;
}
}
We need to pass object of Example class
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'
you can use putExtra(Serializable..) and getSerializableExtra() methods to pass and retrieve objects of your class type; you will have to mark your class Serializable and make sure that all your member variables are serializable too...
Create Android Application
File >> New >> Android Application
Enter Project name: android-pass-object-to-activity
Pakcage: com.hmkcode.android
Keep other defualt selections, go Next till you reach Finish
Before start creating the App we need to create POJO class “Person” which we will use to send object from one activity to another. Notice that the class is implementing Serializable interface.
Person.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 + "]";
}
}
Two Layouts for Two Activities
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>
Two Activity Classes
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)AnotherActivity.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());
}
}
I know this is late but it is very simple.All you have do is let your class implement Serializable like
public class MyClass implements Serializable{
}
then you can pass to an intent like
Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);
To get it you simpley call
MyClass objec=(MyClass)intent.getExtra("theString");
Easiest and java way of doing is : implement serializable in your pojo/model class
Recommended for Android for performance view: make model parcelable
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.
In Activity 1:
Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);
In Activity 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.
}
In Service:
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;
}
This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.
By far the easiest way IMHO to parcel objects. You just add an annotation tag above the object you wish to make parcelable.
An example from the library is below 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; }
}
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
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz#gmail.com");
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);
In Koltin
Add kotlin extension in your build.gradle.
apply plugin: 'kotlin-android-extensions'
android {
androidExtensions {
experimental = true
}
}
Then create your data class like this.
#Parcelize
data class Sample(val id: Int, val name: String) : Parcelable
Pass Object with Intent
val sample = Sample(1,"naveen")
val intent = Intent(context, YourActivity::class.java)
intent.putExtra("id", sample)
startActivity(intent)
Get object with intent
val sample = intent.getParcelableExtra("id")
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.

Is it possible to send a custom object with an Intent as an Extra

I'm asking this question: instread of giving a string, a int and so on, can we push a custom object during the creation fo a new Intent?
newActivity.PutExtra("JsonDataResult", business.getJSON());
In fact I have one object constructed thanks to a JSON (from webrequest) , I parse it and I put it on an object.
At this point I'm passing the string returned from the webrequest to another intent but the parsing takes a long time tu be done, so it could be super-cool the ability to pass custom object with intent.
EDIT : I'm using monodroid / xamarin, so
Android.OS.IParcelable cannot be implemented,
Java.IO.ISerializable cannot be implemented.
You can either let your custom classes implement Parcelable (Google says its faster, but you have to do more coding) or Serializable.
Then add your objects to a bundle (or to the "extra"):
Bundle b = new Bundle()
b.putParcelable("myObject",myObject);
b.putSerializable("myObject",myObject);
For info to Parcelablecheckout this
And if you're interested in the difference between Parcelable and Serializable in more detail check out this
I personally prefer the usage of Serializable for simple object-passing, since the code ist not spoiled with so much code.
Edit: ok isn't your question very similar to this then?
As you've specified you're using Monodroid, it looks like it's not straightforward. I did a quick search and found this forum post
Which listed the following solutions to this problem in Monodroid:
Store the custom Object to be passed as a global variable somewhere, and just read it from your second activity
Which is a bit messy and bad practice, but would work.
Or
serialize your class to a string and send the string to the second Activity
Which will be a little more hard work, but better practice
This is an example how to create a Parcelable class:
public class Person implements Parcelable {
private String name;
private String surname;
private String email;
// Get and Set methods
#Override
public int describeContents() {
return hashCode();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(surname);
dest.writeString(email);
}
// We reconstruct the object reading from the Parcel data
public Person(Parcel p) {
name = p.readString();
surname = p.readString();
email = p.readString();
}
public Person() {}
// We need to add a Creator
public static final Parcelable.Creator<person> CREATOR = new Parcelable.Creator<person>() {
#Override
public Person createFromParcel(Parcel parcel) {
return new Person(parcel);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
Give a look here if you want to use Parcelable.

How to send an object from one Android Activity to another using Intents?

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?
If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).
From the docs, a simple example for how to implement is:
// 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 that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).
Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
Then you can pull them back out with getParcelableExtra():
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:
i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);
You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.
In that case you just put the string return value from (new Gson()).toJson(myObject); and retrieve the string value and use fromJson to turn it back into your object.
If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.
You can send serializable object through 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 {
}
For situations where you know you will be passing data within an application, use "globals" (like static Classes)
Here is what Dianne Hackborn (hackbod - a Google Android Software Engineer) had to say on the matter:
For situations where you know the activities are running in the same
process, you can just share data through globals. For example, you
could have a global HashMap<String, WeakReference<MyInterpreterState>>
and when you make a new MyInterpreterState come up with a unique name
for it and put it in the hash map; to send that state to another
activity, simply put the unique name into the hash map and when the
second activity is started it can retrieve the MyInterpreterState from
the hash map with the name it receives.
Your class should implements Serializable or Parcelable.
public class MY_CLASS implements Serializable
Once done you can send an object on putExtra
intent.putExtra("KEY", MY_CLASS_instance);
startActivity(intent);
To get extras you only have to do
Intent intent = getIntent();
MY_CLASS class = (MY_CLASS) intent.getExtras().getSerializable("KEY");
If your class implements Parcelable use next
MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");
I hope it helps :D
implement serializable in your class
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;
}
}
Then you can pass this object in intent
Intent intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity(intent);
int the second activity you can get data like this
Place place= (Place) getIntent().getSerializableExtra("PLACE");
But when the data become large,this method will be slow.
Short answer for fast need
1. Implement your Class to Serializable.
If you have any inner Classes don't forget to implement them to Serializable too!!
public class SportsData implements Serializable
public class Sport implements Serializable
List<Sport> clickedObj;
2. Put your object into Intent
Intent intent = new Intent(SportsAct.this, SportSubAct.class);
intent.putExtra("sport", clickedObj);
startActivity(intent);
3. And receive your object in the other Activity Class
Intent intent = getIntent();
Sport cust = (Sport) intent.getSerializableExtra("sport");
if your object class implements Serializable, you don't need to do anything else, you can pass a serializable object. that's what i use.
There are a couple of ways by which you can access variables or objects in other classes or Activity.
A. Database
B. shared preferences.
C. Object serialization.
D. A class that can hold common data can be named Common Utilities it depends on you.
E. Passing data through Intents and Parcelable Interface.
It depends upon your project needs.
A. Database
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions, and prepared statements.
Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html
B. Shared Preferences
Suppose you want to store username. So there will be now two things a Key Username, Value Value.
How to store
// Create an 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();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
How to fetch
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");
http://developer.android.com/reference/android/content/SharedPreferences.html
C. Object Serialization
Object serialization is used if we want to save an object state to send it over the network or you can use it for your purpose also.
Use java beans and store in it as one of his fields and use getters and setter for that
JavaBeans are Java classes that have properties. Think of
properties as private instance variables. Since they're private, the only way
they can be accessed from outside of their class is through methods in the class. The
methods that change a property's value are called setter methods, and the methods
that retrieve a property's value are called getter methods.
public class VariableStorage implements Serializable {
private String inString ;
public String getInString() {
return inString;
}
public void setInString(String inString) {
this.inString = inString;
}
}
Set the variable in your mail method by using
VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);
Then use object Serialzation to serialize this object and in your other class deserialize this object.
In serialization, an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
If you want a tutorial for this to refer this link
http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html
Get variable in other classes
D. CommonUtilities
You can make a class by your self which can contain common data which you frequently need in your project.
Sample
public class CommonUtilities {
public static String className = "CommonUtilities";
}
E. Passing Data through Intents
Please refer to this tutorial for this option of passing data.
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
You can use android BUNDLE to do this.
Create a Bundle from your class like:
public Bundle toBundle() {
Bundle b = new Bundle();
b.putString("SomeKey", "SomeValue");
return b;
}
Then pass this bundle with INTENT.
Now you can recreate your class object by passing bundle like
public CustomClass(Context _context, Bundle b) {
context = _context;
classMember = b.getString("SomeKey");
}
Declare this in your Custom class and use.
Thanks for parcelable help but i found one more optional solution
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;
}
}
In Activity One
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);
Get Data In Activity 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());
}
I use Gson with its so powerful and simple api to send objects between activities,
Example
// 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 functions you add them to the objects that you want to send
Usage
Send Object From A to 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);
Receive In 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);
}
I use it almost in every project i do and I have no performance issues.
I struggled with the same problem. I solved it by using a static class, storing any data I want in a HashMap. On top I use an extension of the standard Activity class where I have overriden the methods onCreate an onDestroy to do the data transport and data clearing hidden. Some ridiculous settings have to be changed e.g. orientation-handling.
Annotation:
Not providing general objects to be passed to another Activity is pain in the ass. It's like shooting oneself in the knee and hoping to win a 100 metres. "Parcable" is not a sufficient substitute. It makes me laugh... I don't want to implement this interface to my technology-free API, as less I want to introduce a new Layer... How could it be, that we are in mobile programming so far away from modern paradigm...
In your first Activity:
intent.putExtra("myTag", yourObject);
And in your second one:
myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");
Don't forget to make your custom object Serializable:
public class myCustomObject implements Serializable {
...
}
Another way to do this is to use the Application object (android.app.Application). You define this in you AndroidManifest.xml file as:
<application
android:name=".MyApplication"
...
You can then call this from any activity and save the object to the Application class.
In the FirstActivity:
MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);
In the SecondActivity, do :
MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);
This is handy if you have objects that have application level scope i.e. they have to be used throughout the application. The Parcelable method is still better if you want explicit control over the object scope or if the scope is limited.
This avoid the use of Intents altogether, though. I don't know if they suits you. Another way I used this is to have int identifiers of objects send through intents and retrieve objects that I have in Maps in the Application object.
in your class model (Object) implement Serializable, for
Example:
public class MensajesProveedor implements Serializable {
private int idProveedor;
public MensajesProveedor() {
}
public int getIdProveedor() {
return idProveedor;
}
public void setIdProveedor(int idProveedor) {
this.idProveedor = idProveedor;
}
}
and your first Activity
MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("mensajes",mp);
startActivity(i);
and your second Activity (NewActivity)
MensajesProveedor mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");
good luck!!
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];
}
};
}
Passing the data:
Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
intent.putExtras(bundle);
startActivity(intent);
Retrieving the data:
Bundle bundle = getIntent().getExtras();
dataList2 = getIntent().getExtras().getParcelableArrayList("data");
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();
Using google's Gson library you can pass object to another activities.Actually we will convert object in the form of json string and after passing to other activity we will again re-convert to object like this
Consider a bean class like this
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;
}
}
We need to pass object of Example class
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'
you can use putExtra(Serializable..) and getSerializableExtra() methods to pass and retrieve objects of your class type; you will have to mark your class Serializable and make sure that all your member variables are serializable too...
Create Android Application
File >> New >> Android Application
Enter Project name: android-pass-object-to-activity
Pakcage: com.hmkcode.android
Keep other defualt selections, go Next till you reach Finish
Before start creating the App we need to create POJO class “Person” which we will use to send object from one activity to another. Notice that the class is implementing Serializable interface.
Person.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 + "]";
}
}
Two Layouts for Two Activities
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>
Two Activity Classes
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)AnotherActivity.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());
}
}
I know this is late but it is very simple.All you have do is let your class implement Serializable like
public class MyClass implements Serializable{
}
then you can pass to an intent like
Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);
To get it you simpley call
MyClass objec=(MyClass)intent.getExtra("theString");
Easiest and java way of doing is : implement serializable in your pojo/model class
Recommended for Android for performance view: make model parcelable
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);
If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.
In Activity 1:
Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);
In Activity 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.
}
In Service:
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;
}
This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.
By far the easiest way IMHO to parcel objects. You just add an annotation tag above the object you wish to make parcelable.
An example from the library is below 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; }
}
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
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz#gmail.com");
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);
In Koltin
Add kotlin extension in your build.gradle.
apply plugin: 'kotlin-android-extensions'
android {
androidExtensions {
experimental = true
}
}
Then create your data class like this.
#Parcelize
data class Sample(val id: Int, val name: String) : Parcelable
Pass Object with Intent
val sample = Sample(1,"naveen")
val intent = Intent(context, YourActivity::class.java)
intent.putExtra("id", sample)
startActivity(intent)
Get object with intent
val sample = intent.getParcelableExtra("id")
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.

Categories

Resources