I am making an app with questions and answers, a knowledge game if you will. I created a database schema and a Question object.
There is an enormous amount of duplicate code. It was fine when I had 2 tables, but I added 4 more and now it's almost 400 lines of code. Aside from the final strings which are SQLite code, how can I reduce the amount of duplicate code?
This is where I add questions (I have 5 more for the rest of 5 games):
private void addQuestionToGame1(Question question) {
ContentValues contentValues = new ContentValues();
contentValues.put(QuestionsTable.COLUMN_QUESTION, question.getQuestion());
contentValues.put(QuestionsTable.COLUMN_ANSWER1, question.getAnswer1());
contentValues.put(QuestionsTable.COLUMN_ANSWER2, question.getAnswer2());
contentValues.put(QuestionsTable.COLUMN_ANSWER3, question.getAnswer3());
contentValues.put(QuestionsTable.COLUMN_ANSWER4, question.getAnswer4());
contentValues.put(QuestionsTable.COLUMN_CORRECT_ANSWER_ID, question.getCorrectAnswerID());
db.insert(QuestionsTable.TABLE_NAME1, null, contentValues);
}
This is where I get them as ArrayList (again, I have 5 of these):
@SuppressLint("Range")
public ArrayList<Question> getAllBeginnerGame1() {
ArrayList<Question> questionsArrayList = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME1, null);
if (c.moveToFirst()) {
do {
Question question = new Question();
question.setQuestion(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_QUESTION)));
question.setAnswer1(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER1)));
question.setAnswer2(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER2)));
question.setAnswer3(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER3)));
question.setAnswer4(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER4)));
question.setCorrectAnswerID(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_CORRECT_ANSWER_ID)));
questionsArrayList.add(question);
} while (c.moveToNext());
}
c.close();
return questionsArrayList;
}
Just because a different TABLE_NAME, I am forced to duplicate code for the other tables. Is there a way around this?