我正在尝试在我的sqlite数据库中插入日期选择器和时间选择器中的值。我已将日期和时间存储在对象变量中,然后在我的DBhandler类中调用一个方法,以通过contentvalue对象插入它们。
现在我失败的地方是实际的插入和数据类型。
我在'timeApp'和'dateApp'的以下代码中收到错误我将这些变量作为DATE和TIME变量传递给createAppointmentEntry'方法。:
错误讯息:
The method put(String, String) in the type ContentValues is not applicable for the arguments (String, Time)
发生错误的方法:
public void createAppointmentEntry(String nameApp, String typeApp, Time timeApp, Date dateApp ,String commentApp, Boolean onOrOff) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAMEAPP, nameApp);
cv.put(KEY_TYPEAPP, typeApp);
//ERROR on the following two 'puts'
cv.put(KEY_TIMEAPP, timeApp);
cv.put(KEY_DATEAPP, dateApp);
cv.put(KEY_COMMENTAPP, commentApp);
cv.put(KEY_ALARM, onOrOff);
ourDatabase.insert(DATABASE_TABLE, null, cv);
继承我的数据库专栏:
public static final String KEY_ROWAPPID = "_appid";
public static final String KEY_NAMEAPP = "app_name";
public static final String KEY_TYPEAPP = "app_type";
public static final String KEY_TIMEAPP = "app_time";
public static final String KEY_DATEAPP = "app_date";
public static final String KEY_COMMENTAPP = "app_comments";
public static final String KEY_ALARM = "app_alarm";
我的onCreate方法:
db.execSQL("CREATE TABLE " + DATABASE_TABLEAPP + " (" +
KEY_ROWAPPID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAMEAPP + " TEXT NOT NULL, " +
KEY_TYPEAPP + " TEXT NOT NULL, " +
KEY_TIMEAPP + " TEXT NOT NULL, " +
KEY_DATEAPP + " TEXT NOT NULL, " +
KEY_COMMENTAPP + " TEXT NOT NULL, " +
KEY_ALARM + "BOOLEAN NOT NULL);"
);
以下是我如何设置时间和日期对象变量:
Date setDate = new Date(dobYear - 1900, dobMonth, dobDate);
Time timeToSet = new Time();
timeToSet.set(0, dobMinute, dobHour);
答案 0 :(得分:1)
从编译错误和ContentValues
的API来看,似乎ContentValues
仅支持原始类型String
和byte[]
。所以,尝试替换:
//ERROR on the following two 'puts'
cv.put(KEY_TIMEAPP, timeApp);
cv.put(KEY_DATEAPP, dateApp);
使用:
cv.put(KEY_TIMEAPP, timeApp.toString());
cv.put(KEY_DATEAPP, dateApp.toString());
您可以使用格式化工具将Time
和Date
格式化为标准String
,以便能够将其解析回来。
答案 1 :(得分:0)
我猜想但是我不确定
KEY_ALARM + "BOOLEAN NOT NULL);"
你错过了创建声明的空白。尝试删除它并使用空格重新创建它。
db.execSQL("CREATE TABLE " + DATABASE_TABLEAPP + " (" +
KEY_ROWAPPID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAMEAPP + " TEXT NOT NULL, " +
KEY_TYPEAPP + " TEXT NOT NULL, " +
KEY_TIMEAPP + " TEXT NOT NULL, " +
KEY_DATEAPP + " TEXT NOT NULL, " +
KEY_COMMENTAPP + " TEXT NOT NULL, " +
KEY_ALARM + " BOOLEAN NOT NULL);"
KEY_ALARM + " BOOLEAN NOT NULL);"
昨天做了同样的错误。
如果您写了一个Helperclass,只需更改DATABASE_VERSION
Else,拨打db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLEAPP);
Helper类会将其称为例如
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLEAPP);
onCreate(db); //recreate
}
使用新语句自动重新创建数据库。