-3

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 .

Monir
  • 53
  • 2
  • 9
  • Use one of the formats listed here: https://www.sqlite.org/lang_datefunc.html – Shawn Apr 30 '19 at 19:25
  • Also didn't you already ask this earlier today and have it closed as a duplicate? – Shawn Apr 30 '19 at 19:27
  • 1
    Duplicate of https://stackoverflow.com/q/218384/6296561 – Zoe Apr 30 '19 at 19:38
  • It's not the same error that's why i reposted . You should read the question not only the title Mr Zoe – Monir Apr 30 '19 at 19:47
  • So could you stop telling me it's duplicate I've written 3 different question and still not having an answer from you , you keep telling me it's duplicated and it's not so please just take a look . – Monir Apr 30 '19 at 19:50
  • 1
    @Monir did you read that stack trace you posted? Do you not understand how that's relevant to the post your question keeps being closed as a duplicate of? – Shawn Apr 30 '19 at 20:12
  • @Shawn i don't know why it keeps being closed as a duplicate it's not only about null pointer I was asking how to retreive the date and time ? I've 3 questions about how to use date and time class – Monir Apr 30 '19 at 20:19
  • Date and time are nothing but integers(mostly). You can store their state in integer form. To retrieve, simply get an instance of a calendar and load it up with the read values from DB? – Taseer Apr 30 '19 at 20:24
  • @TaseerAhmad I have to store in the DB , and how to store a date in integer form ? I was asking how to retreive the information of the CalenderView and store it into Date Class – Monir Apr 30 '19 at 20:35
  • 1
    What exactly is your question? I see much code, but not a specific problem. Exchanging date and time between Java and a database have covered many many times already. How have all the thousands of existing posts here not addressed your issue? How is your Question here distinct? Always search Stack Overflow before posting. – Basil Bourque Apr 30 '19 at 22:03
  • @Basil Bourque I’ve searched before and didn’t found any solution. You could just read the two questions and then judge my post. – Monir Apr 30 '19 at 22:13
  • So to be clear , my problem is how to convert date from the calendar view to a date class ? And from TimePicker to time ? Then Store this 2 informations into my DB and the code is for helping to specify my need . Thank you all of you friends and sorry if my questions wasn’t clear . If I’ve found a solution to my problem I wouldn’t post it but It has been two days that I searched and no solution. Thank you . Maybe I didn’t search well. – Monir Apr 30 '19 at 22:17

1 Answers1

0

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: <<<<<
MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Thank u very much – Monir May 01 '19 at 21:58
  • good afternoon How can I store each one in variable ? Not at the same ? Thank you – Monir May 03 '19 at 15:25
  • If you look that's already done the one value "the date" is used to get the date and also the time via SimpleDateFormat's for the display e.g. `showtime.setText(sdfTime.format(cal.getTime()));` – MikeT May 03 '19 at 20:29