Say I have an reference to an object, how should I go about passing this from one Activity to another?
I don't want to have to query the Application Object / singletons / static variables.
Is this still possible?
You can't serialise a class that doesn't implement Serializable , but you can wrap it in a class that does. To do this, you should implement readObject and writeObject on your wrapper class so you can serialise its objects in a custom way. First, make your non-serialisable field transient .
putExtra() method is used for send the data, data in key-value pair key is variable name and value can be Int, String, Float etc. getStringExtra() method is for getting the data(key) which is send by above method. according the data type of value there are other methods like getIntExtra(), getFloatExtra()
This example demonstrates how to pass an object from one activity to another on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
A non-serializable value is a complex object, like a class instance or a function. It is not an array, a plain serializable object, nor a primitive (like strings, numbers, booleans, null, etc.).
You can declare a static variable in another activity, or some Global Variable in Application class, then access it to any activity, like you want to parse some Object of Type NewType, to Class NewActivity, from OldActivity. Do as Following:
Declare an Object of Static NewType in NewActivity.java.
public static NewObject newObject=null;
do Following, when you invoke NewActivity.
NewActivity.newObject=item;
Intent intent=new Intent(OldActivity.this, NewActivity.class);
startActivity(intent);
You can do it in one of the following ways :
Here's an eg from the docs : you can wrap your object with a parcelable
, attach it to an intent, and 'un-wrap' it in the recieving activity.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With