我的方法getHighScore()中的光标返回一个空值,我不知道为什么。我用过
system.out.println(cursor.moveToFirst());
并打印错误。当我在SQLiteman中运行查询时,它返回一个结果。
这是我全班同学。我把伪数据放入包中。
public class DatabaseHandler extends SQLiteOpenHelper{
// Static Database Information
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "quiz_db.db";
public final static String DATABASE_PATH = "/data/data/com.example.app/databases/quiz_db.db";
private static final String QUESTION_TABLE = "Questions";
private static final String SCORE_TABLE = "Score";
// Questions Table Column Names
private static final String Q_ID = "id";
private static final String Q_QUESTION = "question";
private static final String Q_ANSWER1 = "answer_one";
private static final String Q_ANSWER2 = "answer_two";
private static final String Q_ANSWER3 = "answer_three";
private static final String Q_ANSWER4 = "answer_four";
private static final String Q_CORRECT = "correct_answer";
// Score Table Column Names
private static final String S_ID = "id";
private static final String S_SCORE = "score";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_QUESTION_TABLE = "CREATE TABLE " + QUESTION_TABLE + "("
+ Q_ID + " INTEGER PRIMARY KEY," + Q_QUESTION + " TEXT,"
+ Q_ANSWER1 + " TEXT" + Q_ANSWER2 + " TEXT" + Q_ANSWER3 + " TEXT" + Q_ANSWER4 + " TEXT" + Q_CORRECT + " TEXT" +
")";
String CREATE_SCORE_TABLE = "CREATE TABLE " + SCORE_TABLE + "("
+ S_ID + " INTEGER," + S_SCORE + " INTEGER"
+ ")";
db.execSQL(CREATE_QUESTION_TABLE);
db.execSQL(CREATE_SCORE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + QUESTION_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + SCORE_TABLE);
// Create tables again
onCreate(db);
}
// Get High Score
public int getHighScore () {
int score = 0;
String query = "SELECT score FROM " + SCORE_TABLE + ";";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
score = cursor.getInt(cursor.getColumnIndex("score"));
}
cursor.close();
return score;
}
我的数据库位于“assets”文件夹中,文件名为“quiz_db.db”