我不明白问题出在哪里,看看我的代码。
注意的构造函数,接受对象类型Date:
public Nota(String titolo, String testo, Date data, int colore) {
this.titolo = titolo;
this.testo = testo;
this.data = data;
// controlla che l'id del radiobutton non sia -1
if( colore == -1 ){
Log.w("Color", "Errore id Colore del Radio Button");
}else{
this.colore = colore;
}
}
当在数据库中保存注释时,日期被传递到此处:
private void insertInDB() {
DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ITALY);
Calendar now = Calendar.getInstance(Locale.ITALY);
Date date = now.getTime();
String dteStr = rifDate.getText().toString();
// provo a parsare una String in Date
try{
date = format.parse(rifDate.getText().toString());
// cattura l'eccezione
}catch (ParseException pe){
pe.printStackTrace();
}
nota = new Nota(rifTitleNote.getText().toString(), rifWriteEdit.getText().toString(), date, idRadioGroup);
now.setTime(date);
// if the insertion is successful ok, otherwise return -1
boolean insNoteCheck = dbNote.insertNote(nota);
}
这里是继承 SQLiteOnHelper 的 Database 类中的 insert 方法:
public boolean insertNote(Nota nota){
// boolean inizializzat a false utilizzata come return
boolean resultInsert = false;
// repository dei dati in modalità scrittura
SQLiteDatabase dbLite = this.getWritableDatabase();
// utilizza un ContentValues come mappa di valori, dove le columns rappresentano le chiavi
ContentValues values = new ContentValues();
values.put("titoloNota", nota.getTitolo());
values.put("testoNota", nota.getTesto());
values.put("dataNota", nota.getData()); // getData() return a String
values.put("coloreNota", nota.getColore());
方法 getData() 返回一个字符串:
public String getData() {
SimpleDateFormat formatter = new SimpleDateFormat("dd/M/yyyy", Locale.ITALY);
return DateFormat.getDateInstance().format(data); // data is Data type passed to the Constructor
}
然后,我有一个 DatePickerDialog 的内部静态类,我在其中设置日期的 EditText,这里是方法 onDateSet():
public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
EditText date = (EditText) getActivity().findViewById(R.id.editData);
//System.out.println("QUESTA DATAA :"+ anno + " " + mese + " " + giorno);
// setto il testo della Data aggiungendo +1 al mese poichè in Calendar sono rappresentati(0-11)
date.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
最后我有一个用于元素列表的适配器,在方法onBindViewHolder()中,有这一行用于显示列表中的日期
holder.txtDate.setText("Data: " + arrayList.get(position).getDataa());
我已经做了好几次才明白问题所在,但遗憾的是没有办法。 在 Logcat 中创建注释时,通过 System.out.println() 我可以正确看到日期。 但我的印象是日期不会保存在DB中,事实上在列表(适配器)中,日期都初始化为1/gen/1970。
最佳答案
根据此链接Datatypes in SQLLite
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
因此,存储日期的一种方法是使用 INTEGER 作为列类型。然后使用 date.getTime() 获取纪元时间,即以毫秒为单位的 long 类型的纪元时间,作为要存储的值。
从数据库读取时,使用date.setTime(long)设置日期变量。
关于java - Android,日期不保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29526448/