I want to pass realtime object from fragment
to fragment
.
I dont want to pass data.
I dont found way to do that.
The only way that I think is by intent but I am not sure.
i read about Singleton pattern,interfaces and Bundle,Global varible.
I would like to see example if it is possible to use share/pass object from one fragment
to secend fragment
. many Thanks.
Passing real objects between activities or fragments can be achieved through implementing model beans Parcelable
or Serializable
interface.
Parcelable: A Parcel is similar to a Bundle, but is more sophisticated and can support more complex serialization of classes. Applications can implement the Parcelable
interface to define application-specific classes that can be passed around, particularly when using Services.
You can see how to implement Parcelable interface in this article here.
public class Foo implements Parcelable {
...
}
Serializable: A serializable interface is java standard serialization. You can read more about it here.
public class Foo implements Serializable {
private static final long serialVersionUID = 0L;
...
}
Suppose you have a class Foo
implements Parcelable properly, to put it into Intent in an Activity:
Intent intent = new Intent(getBaseContext(), NextActivity.class);
Foo foo = new Foo();
intent.putExtra("foo", foo);
startActivity(intent);
To get it from intent in another activity:
Foo foo = (Foo) getIntent().getExtras().getParcelable("foo");
** EDIT **
As the original question asked for Fragments, then this is how it works:
Fragment fragment = new Fragment();
Foo foo = new Foo();
Bundle bundle = new Bundle();
bundle.putParcelable("Foo", foo);
fragment.setArguments(bundle);
To get it from bundle in another fragment:
Foo foo = (Foo) bundle.getParcelable("Foo");
Hope this helps!
First of all, you have to make your model class as Parcelable:
class Car implements Parcelable
Then implements the override functions of Parcelable class: e-g
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
}
From First Fragment:
// Set data to pass
MyFragment fragment = new MyFragment(); //Your Fragment
Car car = new Car(); // Your Object
Bundle bundle = new Bundle();
bundle.putParcelable("carInfo", car) // Key, value
fragment.setArguments(bundle);
// Pass data to other Fragment
getFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.commit();`
On Second Fragment
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
Car receivedCar = bundle.getParcelable("carInfo"); // Key
}
}
Hope it will help :)
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