Suppose I want to store a custom object of type MyObject in an Intent. The way to do this is to make MyObject implement Parcelable. If one of the fields of MyObject is also a custom object of type Widget the obvious thing to do is to make Widget implement Parcelable too.
The trouble is that there is a huge amount of boilerplate involved when implementing Parcelable. You can get around this by not making Widget implement Parcelable but instead just giving it a constructor taking a Parcel and a method writeToParcel as follows:
public final class Widget {
private final int a;
private final String b;
Widget(Parcel in) {
a = in.readInt();
b = in.readString();
}
void writeToParcel(Parcel out) {
out.writeInt(a);
out.writeString(b);
}
}
You can then have a Widget field in a Parcelable object as follows:
public class MyObject implements Parcelable {
private final int x;
private final Widget w;
MyObject(int x, Widget w) {
this.x = x;
this.w = w;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(x);
w.writeToParcel(out);
}
public static final Parcelable.Creator<MyObject> CREATOR
= new Parcelable.Creator<MyObject>() {
#Override
public MyObject createFromParcel(Parcel in) {
return new MyObject(in.readInt(), new Widget(in));
}
#Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
}
Is this an acceptable approach? Is it considered unidiomatic android to have many custom classes in a project that can be written to and read from Parcels without them actually implementing Parcelable? Or does the fact that I am using a Parcelable to pass complex objects with many fields of custom types (which in turn have many fields of custom type etc etc), indicate that I shouldn't be using Parcelable in the first place?
I would (and did) go with Parceler: https://github.com/johncarl81/parceler
Parceler is a code generation library that generates the Android
Parcelable boilerplate source code. No longer do you have to implement
the Parcelable interface, the writeToParcel() or createFromParcel() or
the public static final CREATOR. You simply annotate a POJO with
#Parcel and Parceler does the rest.
It's really easy to use.
It is recommended to use Parcelable when dealing with passing custom Objects through intents in Android. There isn't an "easy" work around. Since you are dealing with just one extra level of a custom Object (Widget), I would recommend you make Widget Parcelable also. You can also check out this link to see why it is the better approach than using default Serialization. https://coderwall.com/p/vfbing/passing-objects-between-activities-in-android
If your classes are beans, the best solution is the accepted one. If not, I have found that you can (slightly) reduce the pain of implementing Parcelable by creating abstract classes ParcelablePlus and CreatorPlus like this.
ParcelablePlus:
abstract class ParcelablePlus implements Parcelable {
#Override
public final int describeContents() {
return 0;
}
}
CreatorPlus:
abstract class CreatorPlus<T extends Parcelable> implements Parcelable.Creator<T> {
private final Class<T> clazz;
CreatorPlus(Class<T> clazz) {
this.clazz = clazz;
}
#Override
#SuppressWarnings("unchecked")
public final T[] newArray(int size) {
// Safe as long as T is not a generic type.
return (T[]) Array.newInstance(clazz, size);
}
}
Then the Widget class becomes:
public final class Widget extends ParcelablePlus {
private final int a;
private final String b;
Widget(int a, String b) {
this.a = a;
this.b = b;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(a);
out.writeString(b);
}
public static final Creator<Widget> CREATOR = new CreatorPlus<Widget>(Widget.class) {
#Override
public Widget createFromParcel(Parcel in) {
return new Widget(in.readInt(), in.readString());
}
};
}
Related
Hey guys ive found some tutorials about sending non primitive object to activity via intent. But see only that they have members of only primitive in all examples.
I have a class with members that are user data types.
How do i send an object with implementing Parcelable with non primitive instance variables like arraylist etc?
Thanks
The objects that are members of your class must also be Parcelable (or Serializable), and any objects they include must also be Parcelable (or Serializable). To summarize, a Parcelable object must have fields that are either: primitives, Parcelable objects (and their supported collections such as Map or ArrayList) or Serializable objects(and their supported collections such as Map or ArrayList).
A sample piece of code demonstrating this (the Foo class is a Parcelable which contains Bar, which is also Parcelable), is the following (in Java):
import android.os.Parcel;
import android.os.Parcelable;
public class Foo implements Parcelable {
private int primitive;
private Bar object;
public Foo() {
primitive = 0;
object = null;
}
private Foo(final Parcel in) {
primitive = in.readInt();
object = in.readParcelable(Bar.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(primitive);
dest.writeParcelable(object, flags);
}
public static final Parcelable.Creator<Foo> CREATOR = new Parcelable.Creator<Foo>() {
public Foo createFromParcel(Parcel in) {
return new Foo(in);
}
public Foo[] newArray(int size) {
return new Foo[size];
}
};
}
and the Bar class:
import android.os.Parcel;
import android.os.Parcelable;
public class Bar implements Parcelable {
private String attribute;
public Bar() {
attribute = "";
}
private Bar(final Parcel in) {
attribute = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(attribute);
}
public static final Parcelable.Creator<Bar> CREATOR = new Parcelable.Creator<Bar>() {
public Bar createFromParcel(Parcel in) {
return new Bar(in);
}
public Bar[] newArray(int size) {
return new Bar[size];
}
};
}
I'm using the class Tests as the base class, the I created three more classes, Test1, Test2, Test3, they extends Tests class, then I have one more class, States which has an Arraylist.
States is used to gather a bunch of info including a list with the tests I want to perform, so I use the Arraylist and the method "add" to add test1, test2, or test3 to the list, then I want to send this State object to the activity B. I've implemented the parcelable interface on classes Test1, Test2, Test3 and States but I'm getting the next exception:
Unmarshalling unknown type code 6357090 at offset 300
Please, can suggest any way to achieve this, It's important to gather the tests on the arraylist, i think there lies the problem, thanks.
Sorry, this is too long for a comment, so I posted as an answer
Since Test1 extends Tests, Tests should haveit's own Parcelable implementation.
This implementation is the called by all its 'child' classes by using super. For example (this is what I use in my apps):
Tests class
public class Tests implements Parcelable {
private int Id;
private String Name;
// parcelable
protected Tests(Parcel in) {
Id = in.readInt();
Name = in.readString();
}
public static final Creator<Tests> CREATOR = new Creator<Tests>() {
#Override
public Tests createFromParcel(Parcel in) {
return new Tests(in);
}
#Override
public Tests[] newArray(int size) {
return new Tests[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(Id);
dest.writeString(Name);
}
}
Test1 class
public class Test1 extends Tests implements Parcelable {
private int Score;
// parcelable
protected Test1(Parcel in) {
super(in);
Score = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(Score);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Test1> CREATOR = new Creator<Test1>() {
#Override
public Test1 createFromParcel(Parcel in) {
return new Test1(in);
}
#Override
public Test1[] newArray(int size) {
return new Test1[size];
}
};
}
I am using the GCM network manager and I want to pass the service (specifically to the onRunTask(TaskParams taskParams) some objects. From the documentation taskParams are simply a string and a bundle but I want to pass more complex objects.
How can this be done?
Thank you!
One way is to have your custom object implement the Parcelable interface and use Bundle.putParcelable/Bundle.getParcelable.
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).
For example:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
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();
}
}
Also you can read Parcelable vs Serializable
I am implementing Parcelable in order to transmit some simple data throughout an Intent.
However, There is one method in the Parcelable interface that I don't understand at all : newArray().
It does not have any relevant documentation & is not even called in my code when I parcel/deparcel my object.
Sample Parcelable implementation :
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
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();
}
}
So, my question is : what is this method for ? and when is it called ?
Is there any point in doing something else than return new MyParcelable[size]; in that method ?
this is a function to be called when you try to deserialize an array of Parcelable objects and for each single object createFromParcel is called.
It is there to prepare the typed array without all the generics stuff. That's it.
Returning just the standard return new MyParcelable[size]; is fine.
It is normal, that you never call it yourself. However, by calling something like Bundle.getParcelableArray() you end up in this method indirectly.
newArray is responsible to create an array of our type of the appropriate size
In my application I am fetching data from JavaScript, as it is not possible to return the data as an array or object, I am returning it as a String.
Now to organize the data I am creating a class which contains ArrayLists and other string variables and further I am creating array of my class objects variable to store multiple records.
public class Data {
ArrayList<String> m_empArrayList = new ArrayList();
ArrayList<String> m_depArrayList = new ArrayList();
String m_time;
String m_duration;
}
Data d = new Data();
What would be a good approach to pass the data between Activities? As Intents and ShredPrefrences are used to pass small units of data I am not considering it here.
Implement the Parcelable interface in your custom object and transmit it via an Intent.
Here is an example of a Parcelable object.
public class MyObject implements Parcelable {
private String someString = null;
private int someInteger = 0;
public MyObject() {
// perform initialization if necessary
}
private MyObject(Parcel in) {
someString = in.readString();
someInteger = in.readInt();
}
public static final Parcelable.Creator<MyObject> CREATOR =
new Parcelable.Creator<MyObject>() {
#Override
public MyObject createFromParcel(Parcel source) {
return new MyObject(source);
}
#Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
// Getters and setters
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(someString);
dest.writeInt(someInteger);
}
}
Here is what happens. If you implement the Parcelable interface you have to create a private constructor which takes a Parcel as a parameter. That Parcel holds all the serialized values.
You must implement the nested class Parcelable.Creator with the name CREATOR as this is going to be called by Android when recreating your object.
The method describeContents() is only of use in special cases. You can leave it as it is with a return value of 0.
The interesting action happens in writeToParcel() where you, as the name tells, write your data to a Parcel object.
Now you can just add your custom object directly to an Intent like in this example.
MyObject myObject = new MyObject();
Intent i = new Intent();
i.setExtra("MY_OBJECT", myObject);
// implicit or explicit destination declaration
startActivity(i);
you can use Application class present in Android to pass data between activities.
here is a good link..http://www.helloandroid.com/tutorials/maintaining-global-application-state