Android SQLite数据库空指针

时间:2015-03-14 15:10:59

标签: java android sqlite

我有一个SQLite帮助器类,我试图用来添加"问题"进入数据库。这是班级:

public class QuestionsDBHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "triviaQuiz";
    // tasks table name
    private static final String TABLE_QUESTION = "question";
    // tasks Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_QUES = "question";
    private static final String KEY_ANSWER = "answer"; // correct option
    private static final String KEY_OPTA = "opta"; // option a
    private static final String KEY_OPTB = "optb"; // option b
    private static final String KEY_OPTC = "optc"; // option c
    private static final String KEY_OPTD = "optd"; // option c
    private SQLiteDatabase dbase;

    public QuestionsDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        dbase = db;
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTION + " ( "
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
                + " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_OPTA + " TEXT, "
                + KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT, " + KEY_OPTD + " TEXT)";

        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTION);
        onCreate(db);
    }

    // Adding new question
    public void addQuestion(Question quest) {
        ContentValues values = new ContentValues();
        values.put(KEY_QUES, quest.getQUESTION());
        values.put(KEY_ANSWER, quest.getANSWER());
        values.put(KEY_OPTA, quest.getOPTA());
        values.put(KEY_OPTB, quest.getOPTB());
        values.put(KEY_OPTC, quest.getOPTC());
        values.put(KEY_OPTD, quest.getOPTD());

        // Inserting Row
        if(dbase == null) {
            System.out.println("DB null");
        }
        dbase.insert(TABLE_QUESTION, null, values);
    }

}

以下是我在我的活动中使用它的方法:

QuestionsDBHelper db = new QuestionsDBHelper(this);
db.addQuestion(new Question("Question", "Option 1", "Option 2", "Option 3", "Option 4", "Answer"));

我正在这条线上找到一个空指针:

dbase.insert(TABLE_QUESTION, null, values);

我正在检查

if(dbase == null) {
    System.out.println("DB null");
}

事实证明Dabatase为null。但是在onCreate我正在发送dbase = db,所以我不确定为什么它是空的。有任何想法吗?感谢

1 个答案:

答案 0 :(得分:2)

简单地说,因为并不总是调用onCreate(仅在创建数据库时)。在使用dbase之前,你应该在构造函数或每个方法中放入dbase = getWriteableDatabase()