Reputation: 1867
I have a SQLite helper class that I am trying to use to add "Questions" into a database. Here is the class:
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);
}
}
and here is how I am using it in my Activity:
QuestionsDBHelper db = new QuestionsDBHelper(this);
db.addQuestion(new Question("Question", "Option 1", "Option 2", "Option 3", "Option 4", "Answer"));
and I am getting a Null Pointer on this line:
dbase.insert(TABLE_QUESTION, null, values);
and I'm doing a check
if(dbase == null) {
System.out.println("DB null");
}
and it turns out the Dabatase is null. But in onCreate
I am seeting dbase = db
so I'm not sure why it is null. Any ideas? Thanks
Upvotes: 0
Views: 1158
Reputation: 409
Simply, because onCreate is not always called (only when creating the database). You should put dbase = getWriteableDatabase() in constructor or in every method before working with dbase
Upvotes: 2