如何将日期和时间从Java存储到数据库

时间:2019-04-30 19:17:14

标签: android sqlite android-sqlite

我正在Android Studio中开发一个应用程序,我需要实施一次会议,因此我使用TimePickerDialog和CalenderView添加日期和时间。我想检索这2条信息并将它们存储在myDB中。

1-如何在Java中将CalendarView中的日期存储到Date类中,如何将时间存储到DatePicker中。

2-如何将java类中的日期插入到SQLite中,以及如何插入时间。

这是我的代码

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类

     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;
              }

数据库

   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();

  }

谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个基于您的代码的工作示例:-

利用Calendar和SimpleDateFormat类将日期和时间保存在单个列中,既长(更有效的方式,即占用更少的空间),也保存为String。两者都与SQLite Date and Time functions兼容,因此日期/时间操作轻而易举,因为返回日期和时间几乎是您想要的任何格式。

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) {

    }
}

活动:-

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
    }
}

结果

该应用看起来像:-

enter image description here

单击“确定”后,TextViews显示:-

enter image description here

点击按钮后,该行即被添加并显示在日志中,例如(第二行,之前已添加第一行)

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: <<<<<