我正在尝试阅读最后添加到我的项目SQLiteDatabase
,但是CursorIndexOutOfBoundsException
当我尝试使用该moveToLast()
方法时,我得到了一个。字符串以Fragment
. 添加字符串后,我应该使用单独的类(不是Activity
/ Fragment
)来创建一个带有最后添加的项目的 Toast。
这是代码:
在片段中:
HistoryDataBaseSQL mDbHelper = new HistoryDataBaseSQL(getActivity()); // This gets access to my SQL
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstructData.COLUMN_NAME_ENTRY_ID, counter);
values.put(ConstructData.COLUMN_NAME_TITLE, content_title); // content_title is a variable
这是我的助手类的一部分:
public static abstract class ConstructData implements BaseColumns {
public static final String TABLE_NAME = "history";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
这是我的数据库类:
public class HistoryDataBaseSQL extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "history.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + ConstructData.TABLE_NAME + " (" +
ConstructData._ID + " INTEGER PRIMARY KEY," +
ConstructData.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
ConstructData.COLUMN_NAME_TITLE + TEXT_TYPE +
// Any other options for the CREATE command, rem to add comma_sep to split
" )";
public HistoryDataBaseSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
这是尝试创建的类Toast
:
HistoryDataBaseSQL mDbHelper = new HistoryDataBaseSQL(getContext); // This gets access to my SQL
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
ConstructData._ID,
ConstructData.COLUMN_NAME_TITLE
};
Cursor c = db.query(
ConstructData.TABLE_NAME,
projection,
null,
null,
null,
null,
null
);
c.moveToLast();
String string = null;
string = c.getString(c.getColumnIndexOrThrow(ConstructData.COLUMN_NAME_TITLE)); // If I comment this out, there is not exception
Toast.makeText(getContext, "Title is: " + string, Toast.LENGTH_SHORT).show();
c.close();