Search code examples
androidsqliteandroid-sqlite

How to store date and time from java to the database


I am developping in Android Studio an apps and I need to implement a meeting , so i Use TimePickerDialog and CalenderView to add the date and the time . I want to retreive this 2 informations and store them in myDB .

1- How could I store date from CalendarView to Date class in Java and the same for timePicker.

2-How to insert date from java Class into SQLite and the same for time.

This is my code

RDV_Activity

   CalendarView cv ;
   TextView showTime;
   TimePickerDialog timePicker;
   EditText heure,titre;
   Time time ;
   Date d;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_rdv);

   showTime= (TextView) findViewById(R.id.showTime);
   cv= (CalendarView) findViewById(R.id.cv);
   btn_ajouter = (Button) findViewById(R.id.btn_ajouter);
   heure = (EditText) findViewById(R.id.heure);
   cv.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
     @Override
     public void onSelectedDayChange(@NonNull CalendarView view, int 
   year, int month, int dayOfMonth) {
         String date = dayOfMonth + "/" + (month + 1) + "/" + year ;
         d= new Date(year,month,dayOfMonth);
         System.out.println(d.toString());
     }
    });
   heure.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         final Calendar calendar = Calendar.getInstance();
         final int hour = calendar.get(Calendar.HOUR);
         int minute = calendar.get(Calendar.MINUTE);

         timePicker = new TimePickerDialog(Rdv.this, new 
    TimePickerDialog.OnTimeSetListener() {
             @Override
             public void onTimeSet(TimePicker timePicker, int 
   selectedHour, int selectedMinute) {
                 showTime.setText( selectedHour + ":" + 
       selectedMinute);

             }
         }, hour, minute, true);
         timePicker.setTitle("Choose time");
         time.setHours(hour);
         time.setMinutes(minute);
         System.out.println(""+time.getHours());
         System.out.println(""+1);
         timePicker.show();
         showTime.setText(heure.getText());

     }
     });
   titre = (EditText) findViewById(R.id.titre);

    RDV r = new RDV(d,time,titre.getText().toString());

   }

    }

RDV Class

     private final int idR;
     private  int cpt=0;
     private Date dateR;
     private Time heure ;
     private String titre ;

     public RDV(Date dateR, Time heure, String titre)
    {
        this.dateR = dateR;
        this.heure = heure;
        this.titre = titre;

           cpt++;
        idR = cpt;
              }

DB

   String CREATE_TABLE_RDV = "CREATE TABLE " + table_Rdv + " (" + ID_R + " 
   INTEGER PRIMARY KEY AUTOINCREMENT, "+ TITRE +
        " VARCHAR NOT NULL, " +DATE_R+ " Date NOT NULL, " +HEURE_R+ " 
    Time NOT NULL, " +ID_F+ " INTEGER NOT NULL ,"+
        " CONSTRAINT FK1 FOREIGN  KEY ( " +ID_F+") REFERENCES 
   "+table_Femme+"("+ID_F+") )";
   db.execSQL(CREATE_TABLE_RDV);

  public void insererRdv(RDV r)
     {
   SQLiteDatabase db = this.getWritableDatabase();
   ContentValues vals = new ContentValues();


   vals.put(TITRE,r.getTitre());
   vals.put(HEURE_R,r.getHeure().toString());
   vals.put(DATE_R ,r.getDateR().toString());


   db.insert(table_Rdv,null,vals);
   db.close();

  }

Thank you .


Solution

  • Here's a Working example based upon your code:-

    Which utilises the Calendar and the SimpleDateFormat classes to save the date and time in a single column both as a long (the more efficient way i.e. takes less space) and also as a String. BOTH are compatible with the SQLite Date and Time functions so date/time manipulations are a breeze as is returning dates and time in virtually any format you want.

    The DatabaseHelper

    public class DBHelper extends SQLiteOpenHelper {
    
        public static final String DBNAME = "mydb";
        public static final int DBVERSION = 1;
    
        public static final String table_Rdv = "rdv";
        public static final String ID_R = BaseColumns._ID;
        public static final String TITRE = "titre";
        public static final String DATE_R ="date_r";
        public static final String HEURE_R = "heure_r";
        public static final String ID_F = "id_f";
        public static final String DATETIMELONG = "datetimelong";
        public static final String DATETIMESTRING = "datetimestring";
    
        public DBHelper(Context context) {
            super(context, DBNAME, null, DBVERSION);
            this.getWritableDatabase();
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
    
            String CREATE_TABLE_RDV = "CREATE TABLE " + table_Rdv + " (" +
                    ID_R + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    TITRE + " VARCHAR NOT NULL, " +
                    DATE_R+ " Date NOT NULL, " + //<<<<<<<<<< Column Not needed
                    HEURE_R+ " Time NOT NULL, " + //<< Column not needed
                    // Note only one of the two following columns are needed
                    // Using SQLite date and time functions you can do very much what you want
                    //         see https://www.sqlite.org/lang_datefunc.html
                    DATETIMELONG + " INTEGER, " + //<<<<<<<<<< Column will hold both date and time as long
                    DATETIMESTRING + " TEXT, " + //<<<<<<<<<< Column will hold both date and time as String YYYY-MM-DD HH:MM
                    ID_F+ " INTEGER NOT NULL " +
                    //", CONSTRAINT FK1 FOREIGN  KEY ( " + ID_F + ") REFERENCES "+ table_Femme + "("+ID_F+") " + // Commented out for demo
                    ")";
            db.execSQL(CREATE_TABLE_RDV);
        }
    
        public long addRDVRow(String titre, long datetimelong, String datetimestring) {
            ContentValues cv = new ContentValues();
            cv.put(TITRE,titre);
            cv.put(DATE_R,"NOTHING NEEDED HERE AS NOT USED");
            cv.put(HEURE_R,"NOTHING NEEDED HERE AS NOT USED");
            cv.put(DATETIMELONG,datetimelong);
            cv.put(DATETIMESTRING,datetimestring);
            cv.put(ID_F,0); //<<<<<<<<<< as no fk constraint anything will do for demo so 0
            SQLiteDatabase db = this.getWritableDatabase();
            return db.insert(table_Rdv,null,cv);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
        }
    }
    

    The activity :-

    public class MainActivity extends AppCompatActivity {
    
        CalendarView cv;
        TimePickerDialog timepicker;
        TextView showtime;
        TextView showdatetime; //<<<<<<<<<< ADDED for demo
        Button btn_ajouter;
    
        Calendar cal;
        SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
        int mYear,mMonth,mDay,mHour,mMin;
    
        DBHelper mDBHlpr;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mDBHlpr = new DBHelper(this);
    
            cv = this.findViewById(R.id.cv);
            cal = Calendar.getInstance();
    
            showtime = this.findViewById(R.id.showtime);
            showdatetime = this.findViewById(R.id.showdatetime);
            btn_ajouter = this.findViewById(R.id.btn_ajouter);
            handleDateTime(); // set to show current date time
            handleDate(); // Handle the Calendar View
            handleTime(); // Handle the TimePicker
    
            btn_ajouter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDBHlpr.addRDVRow("Whatever",cal.getTimeInMillis(),sdfFull.format(cal.getTime())); //<<<<<<<<<< Add new row to db
    
                    //for demonstration
                    DatabaseUtils.dumpCursor(
                            mDBHlpr.getWritableDatabase().query(
                                    DBHelper.table_Rdv,
                                    null,null,null,null,null,null
                            )
                    );
                }
            });
        }
    
        public void handleDate() {
            cv.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
                @Override
                public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                    mYear = year;
                    mMonth = month;
                    mDay = dayOfMonth;
                    handleDateTime();
                }
            });
        }
        public void handleTime() {
            showtime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    timepicker = new TimePickerDialog(v.getContext(), new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            mHour = hourOfDay;
                            mMin = minute;
                            handleDateTime();
                        }
                    },mHour,mMin,true);
                    timepicker.setTitle("Pick Time");
                    timepicker.show();
                }
            });
        }
    
        private void handleDateTime() {
            cal.set(mYear,mMonth,mDay,mHour,mMin);
            showtime.setText(sdfTime.format(cal.getTime()));
            showdatetime.setText(sdfFull.format(cal.getTime()) + " or as long " + String.valueOf(cal.getTimeInMillis())); // SQL YYYY-MM-DD HH:MM format
        }
    }
    

    Result

    The app looks like :-

    enter image description here

    After clicking OK the TextViews show :-

    enter image description here

    After Click the Button then the row is added and shown in the log e.g. (2nd row, first was added previously)

    05-01 11:17:40.282 23152-23152/q.so55927409 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@a40a2ab
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: 0 {
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    _id=1
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    titre=Whatever
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    date_r=NOTHING NEEDED HERE AS NOT USED
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    heure_r=NOTHING NEEDED HERE AS NOT USED
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimelong=-125838902353924
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimestring=2019-05-16 15:20
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    id_f=0
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: }
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: 1 {
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    _id=2
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    titre=Whatever
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    date_r=NOTHING NEEDED HERE AS NOT USED
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    heure_r=NOTHING NEEDED HERE AS NOT USED
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimelong=-125838880753924
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    datetimestring=2019-05-16 21:20
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out:    id_f=0
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: }
    05-01 11:17:40.283 23152-23152/q.so55927409 I/System.out: <<<<<