How to pass an instance (object) of TIME using a Bundle???
May be a simple question,but i need a precise answer...
DATE date=new DATE();
1) You can break the object down to its constitute data, and if what's on the other end has knowledge of the same sort of object, it can assemble a clone from the serialized data. That's how most of the common types pass through bundles. 2) You can pass an opaque handle.
Put the data in a Bundle and then use intent to transfer it. Here's how to get the data transferred from a Bundle: Here's how to do it. This side sets the data to death and begins to pass the object Similarly, I put an object in a Bundle and pass it using Intent. Here's how we get the object passed by a Bundle:
For example, unlike integers and strings, you can’t pass objects between activities. For this, you have to flatten the data. There are two options available: Java’s Serializable interface and Android’s Parcelable interface. Which is better? We’ll look at each of them.
Next, use one of the following methods to pass the Bundle to the start destination: If you're creating your NavHost programmatically, call NavHostFragment.create (R.navigation.graph, args) , where args is the Bundle that holds your data. To retrieve the data in your start destination, call Fragment.getArguments ().
Dates are serializable, so you can use get/putSerializable
:
MyFragment fragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(MyFragment.DATE_KEY, new Date());
fragment.setArguments(bundle);
In MyFragment
:
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Bundle bundle = savedInstanceState != null ? savedInstanceState : getArguments();
Date startTime = (Date) bundle.getSerializable(MyFragment.DATE_KEY);
this.time = startTime;
}
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putSerializable(MyFragment.DATE_KEY, this.time);
}
This code is approximate since I am writing it from memory .
Intent mIntent = new Intent(ActivityA.this, ActivityB.class);
mIntent.putLong(KEY, getTimeMilliseconds());
startactivity(mIntent);
Then in the onCreate of ActivityB :
Bundle mBundle = getItent().getExtras();
Long time = mBundle.getLong(KEY);
Note :
putLong / getLong can apply to multiple type String , int ...
If you want it to apply to a custom object you should make that object implement Parcelable.
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