4

I am packing an intent and one of the Extras I add is a date object, like this:

intent.putExtra(DATE_EXTRA, t.getDate());

Later, when I reading the extras, I try to get the Date like this:

this.date = new Date(intent.getExtras().getString(DATE_EXTRA));

However, this returns an error about the String being empty. I don't think the above is the right way to do it, because I am not looking for a string, but I have not been able to find an intent.getDateExtra() method anywhere. What do I do?

I know that the date was passed properly, because I can see it while debugging: enter image description here

AdamMc331
  • 16,492
  • 10
  • 71
  • 133

3 Answers3

15

Replace:

this.date = new Date(intent.getExtras().getString(DATE_EXTRA));

with:

this.date = (Date)intent.getSerializableExtra(DATE_EXTRA);

and see if that helps.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Strange though that you are allowed to put a Date extra but not call `getDateExtra` when I can call getString, getDouble, getLong, etc... – AdamMc331 Nov 30 '14 at 19:38
  • 2
    @McAdam331: "You are a godsend" -- you have a rather unusual god in mind. :-) "when I can call getString, getDouble, getLong, etc" -- `double` and `long` are primitives, and `String` is more popular than `Date`. – CommonsWare Nov 30 '14 at 19:39
0

Another workaround would be to pass the long value of the date:

intent.putExtra(DATE_EXTRA, t.getDate().getTime());
....
this.date = new Date(intent.getLongExtra(DATE_EXTRA, 0)); //0 is the default value
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
0

Safe way in kotlin:

  intent.putExtra("MOVE_DATE", date)

and to read it in safe way by check for key & null check:

 val moveDate: Date?     
 intent?.apply {
 if (hasExtra("MOVE_DATE")) {
       moveDate = getSerializableExtra("MOVE_DATE") as? Date
       moveDate?.let { print(it) }
    }
 }
Hamed Jaliliani
  • 2,789
  • 24
  • 31