我正在尝试将TIMESTAMP列添加到我的SQLite数据库中。该列用于使用" System.currentTimeMillis();"来捕获时间戳数据。应用程序崩溃,错误来自下面显示的** **行中的游标代码。错误读取"无法启动活动ComponentInfo {... ListActivity}:java.lang.IllegalStateException:无法从CursorWindow读取第0行,第6列。在从中访问数据之前,请确保Cursor已正确初始化。"
最初我在模型文件中将变量设置为String。然后我尝试了很长时间,但都没有工作。我在这里缺少什么?
UserData文件:
...
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
DatabaseHelper.java文件:
...
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + DBContract.DBEntry.TABLE_NAME +
"(" + DBContract.DBEntry.COLUMN_NAME_ID +
" INTEGER PRIMARY KEY AUTOINCREMENT,"
+ DBContract.DBEntry.COLUMN_NAME_TODO +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_NOTE1 +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_NOTE2 +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_DUEDATE +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_DUETIME +
" TEXT,"
+ DBContract.DBEntry.COLUMN_NAME_TIMESTAMP +
" TEXT" + ")";
...
public void insertIntoDB(String todo, String note1, String note2, String duedate, String duetime, long timestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBContract.DBEntry.COLUMN_NAME_TODO, todo);
values.put(DBContract.DBEntry.COLUMN_NAME_NOTE1, note1);
values.put(DBContract.DBEntry.COLUMN_NAME_NOTE2, note2);
values.put(DBContract.DBEntry.COLUMN_NAME_DUEDATE, duedate);
values.put(DBContract.DBEntry.COLUMN_NAME_DUETIME, duetime);
values.put(DBContract.DBEntry.COLUMN_NAME_TIMESTAMP, timestamp);
db.insert(DBContract.DBEntry.TABLE_NAME, null, values);
db.close();
}
...
Cursor cursor = db.rawQuery(query,null);
try {
if (cursor.moveToFirst()) {
do {
UserData userData = new UserData();
userData.setTodo(cursor.getString(1));
userData.setNote1(cursor.getString(2));
userData.setNote2(cursor.getString(3));
userData.setDuedate(cursor.getString(4));
userData.setDuetime(cursor.getString(5));
**userData.setTimestamp(cursor.getLong(6));**
modelList.add(0, userData);
} while (cursor.moveToNext());
...
ListAdapter.java文件:
...
public void onBindViewHolder(final ListViewHolder holder, final int position) {
...
holder.cardBlankText5.setText((int) dbList.get(position).getTimestamp());
Activity.java文件:
...
public void onClickSave(View v) {
...
long timestamp=System.currentTimeMillis();
helper = new DatabaseHelper(Activity.this);
helper.insertIntoDB(todo,note1,note2,duedate,duetime,timestamp);
startActivity(new Intent(Activity.this,ListActivity.class));
}
答案 0 :(得分:-1)
将DBContract.DBEntry.COLUMN_NAME_TIMESTAMP
作为DATETIME
类型应该有效。我通常有实用程序方法,它接受游标和列名称并返回Date对象:
public static Date getDateColumn(Cursor c, String column) {
Date d = null;
Long time = c.getLong(c.getColumnIndexOrThrow(column));
if (time != null && time != 0) {
d = new Date();
d.setTime(time);
}
return d;
}
要检查的第二件事是您的查询中是否要求该字段。共享query
的值可能会有所帮助,但是当您要求的列不在预测中时,通常会得到类似的内容。
e.g。从mytable中选择columnA,columnB;然后你试着从columnC得到一些不在结果中的东西。
答案 1 :(得分:-1)
不要尝试从声明为TEXT的列中获取Long。将其声明为INTEGER。 或者使用getString()并将值转换为Long。