DateLens.java

  1. package net.zer0bandwidth.android.lib.database.sqlitehouse.refractor;

  2. import android.content.ContentValues;
  3. import android.database.Cursor;
  4. import android.os.Bundle;

  5. import net.zer0bandwidth.android.lib.database.SQLiteSyntax;

  6. import java.util.Date;

  7. import static net.zer0bandwidth.android.lib.database.SQLiteSyntax.SQLITE_NULL;

  8. /**
  9.  * Marshals {@link java.util.Date} objects.
  10.  *
  11.  * <p>The lens converts all dates into integer GMT timestamps for storage in the
  12.  * DB, then recreates the {@code Date} objects upon retrieval. This is because
  13.  * integer timestamps are more reliably stored and are absolute (no fretting
  14.  * about timezones).</p>
  15.  *
  16.  * @see SQLDateLens
  17.  * @since zer0bandwidth-net/android 0.1.4 (#26)
  18.  */
  19. public class DateLens
  20. extends Lens<Date>
  21. implements Refractor<Date>
  22. {
  23. @Override
  24. public String getSQLiteDataType()
  25. { return SQLiteSyntax.SQLITE_TYPE_INT ; }

  26. /**
  27.  * When a date cannot be null, this class provides a default value at the
  28.  * start of the epoch.
  29.  * @return a {@code Date} initialized at epoch time zero
  30.  */
  31. @Override
  32. public Date getSQLiteDefaultValue()
  33. { return new Date(0) ; }

  34. @Override
  35. public String toSQLiteString( Date o )
  36. {
  37. return ( o == null ? SQLITE_NULL :
  38. Long.toString( o.getTime() ) ) ;
  39. }

  40. @Override
  41. public DateLens addToContentValues( ContentValues vals, String sKey, Date val )
  42. {
  43. vals.put( sKey, val.getTime() ) ;
  44. return this ;
  45. }

  46. /** @since zer0bandwidth-net/android 0.1.7 (#50) */
  47. @Override
  48. public DateLens addToBundle( Bundle bndl, String sKey, Date val )
  49. {
  50. bndl.putLong( sKey, val.getTime() ) ;
  51. return this ;
  52. }

  53. @Override
  54. public Date fromCursor( Cursor crs, String sKey )
  55. {
  56. long ts = crs.getLong( crs.getColumnIndex( sKey ) ) ;
  57. return new Date( ts ) ;
  58. }

  59. /** @since zer0bandwidth-net/android 0.1.7 (#50) */
  60. @Override
  61. public Date fromBundle( Bundle bndl, String sKey )
  62. { return new Date( bndl.getLong( sKey ) ) ; }
  63. }