I've looked at similar questions but non had the same issue I'm having.
My application keeps crashing on addQuestion() method and for the life of me I couldn't pin point down the problem. The error log shows number format exception at line 176 int difficulty = Integer.parseInt(cursor.getString(2));
I reviewed my code very carefully for possible SQL syntax errors but couldn't find anything.
Here's my addQuestion method
public void addQuestion(Question question, String question_type){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT body FROM questions where body = '" +question.getBody()+"'";
Cursor cr = db.rawQuery(query, null);
if(cr.getCount() > 0){
db.close();
return;
}
else {
ContentValues cv = new ContentValues();
cv.put(type, question_type);
cv.put(body, question.getBody());
cv.put(answer, question.getAnswer());
cv.put(difficulty, question.getDifficulty());
try {
db.insert(questions_table, null, cv);
} catch (SQLiteException e) {
e.getMessage();
}
}
db.close();
}
and here's my getQuestion by type method:
public Question getQuestionByType(String type){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT " + body + "," + answer + "," + difficulty + " FROM " + questions_table + " WHERE "
+ this.type + " ='" + type+"';";
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
String body = cursor.getString(0);
String answer = cursor.getString(1);
int difficulty = Integer.parseInt(cursor.getString(2));
db.close();
return new Question(type, body, answer, difficulty);
}
Here's the log output
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:483)
at java.lang.Integer.parseInt(Integer.java:556)
at com.maz.quizzdat.DbHandler.getQuestionByType(DbHandler.java:176)
at com.maz.quizzdat.MainActivity$1.onClick(MainActivity.java:47)
Any help is appreciated.
Edit:
for those of you who may run into a similar situation, you cannot use Integer.parseInt();
in this particular situation on a string, even though the string is in fact a number. Use curser.getInt()
instead of Integer.parseInt(curser.getString())