How to pass an object
of a class
using an intent
?
ex.
MyClass mc = new MyClass();
how can I pass mc
using an intent
?
How to pass an object
of a class
using an intent
?
ex.
MyClass mc = new MyClass();
how can I pass mc
using an intent
?
Parcel is a light weight IPC (Inter Process Communication) data structure, where you can flatten your objects in byte stream.
Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.
1.Implement an Interface android.os.Parcelable which will make Objects of Parcelable class.
2.Overwrite two methods of android.os.Parcelable Interface as bellow :
describeContents()- define the kind of object you are going to Parcel.
writeToParcel(Parcel dest, int flags)- actual object serialization/flattening happens here. You need to individually Parcel each element of the object.
3.Define a variable called CREATOR of type Parcelable.Creator
http://prasanta-paul.blogspot.com/2010/06/android-parcelable-example.html
Serialization in Java is far +too slow+ to satisfy Android’s interprocess-communication requirements. So the team built the Parcelable solution. The Parcelable approach requires that you explicitly serialize the members of your class, but in the end, you get a much faster serialization of your objects.
The problem with Serializable is that it tries to appropriately handle everything under the sun and uses a lot reflection to make determine the types that are being serialized.
Use Serializable Object, and Keep it inside Bundle or Intent Directly
Sending Object
Intent mIntent=new Intent();
mIntent.putExtra("iis",new MyClass());
and your class
private class MyClass implements Serializable{
}
Getting at other End
MyClass mc=(MyClass) getIntent().getExtras().getSerializable("iis");
Updated
you can send data as Parcelable object also. But remember
If you are sending a non-primitive type data/Object to another activity through the intent you have to either Serialize or implement Parcelable for that object. The preferred technique is Parcelable since it doesn't impact the performance
One option could be let your class implement Serializable interface and then you can pass object instances in intent extra using putExtra(Serializable..) variant of the Intent#putExtra() method.
Passing :
intent.putExtra("MyClassObject", obj);
To retrive
getIntent().getSerializableExtra("MyClassObject");
Your class:
public class myClassObject implements Serializable {
public myClassObject(){
}
}
intent passing:
Intent intent = new Intent(MainActivity.this,NextActivity.class);
intent.putExtra("question_data", qData);
intent.putExtra("answer_string", answer);
startActivity(intent);