I'm confused with the objects and constructor in Java. I query from a SQLiteDatabase but I couldn't get the correct object/answer. I know my codes look messy and I need to clean it up but I don't know where to start...
public static class QObject {
public String word;
public String definition;
public QObject(String word, String definition) {
this.word = word;
this.definition = definition;
}
public QObject getAnswer(String message) {
QObject quizObject = null;
String query = "select * from " + TABLE_NAME + " where " + COL_WORD + " = '" + message + "'";
Cursor cursor = this.getDbConnection().rawQuery(query, null);
if(cursor.moveToFirst()) {
do {
String myword = cursor.getString(cursor.getColumnIndexOrThrow(COL_WORD));
String mydefinition = cursor.getString(cursor.getColumnIndexOrThrow(COL_DEFINITION));
quizObject = new QObject(word, definition);
} while (cursor.moveToNext());
}
cursor.close();
return quizObject;
}
private SQLiteDatabase getDbConnection() {
return dbHelper.getReadableDatabase();
}
}
}
public void searchName(View view) {
String word = null;
String definition = null;
DatabaseTable db = new DatabaseTable(this);
DatabaseBackend dbBackend = new DatabaseBackend(MainActivity.this);
DatabaseObject dbo = new DatabaseObject(this);
DatabaseB.QObject quizobject = new DatabaseB.QObject(word, definition);
DatabaseB.QObject allQuizQuestions = quizobject.getAnswer(message);
String answer = allQuizQuestions.definition;
TextView textView = findViewById(R.id.textView2);
textView.setText(answer);
}
The error message is null object reference:
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
...
Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.justkitting.orion.databasetest.MainActivity$DatabaseB$QObject.definition' on a null object reference
at com.justkitting.orion.databasetest.MainActivity.searchName(MainActivity.java:139)
at java.lang.reflect.Method.invoke(Native Method)
...
Many many thanks.