· 7 years ago · Dec 14, 2018, 12:30 AM
1import android.content.ContentValues;
2import android.content.Context;
3import android.database.Cursor;
4import android.database.sqlite.SQLiteDatabase;
5import android.database.sqlite.SQLiteOpenHelper;
6import android.os.Debug;
7import android.util.Log;
8
9import java.util.ArrayList;
10import java.util.Collections;
11import java.util.List;
12
13// class to provide operations with database
14
15public class MyDataBaseHelper extends SQLiteOpenHelper {
16
17 // Database name
18 public static String DATABASE_QUESTION = "QUIZ.db";
19 // Current version of database
20 private static final int DATABASE_VERSION = 1;
21 // Database table name
22 private static final String TABLE_QUESTION = "QuestionBank";
23 private static final String TABLE_USER = "Users";
24 // All fields used in question table
25 private static final String KEY_ID_QUESTION = "id";
26 private static final String QUESTION = "question";
27 private static final String CHOICE1 = "choice1";
28 private static final String CHOICE2 = "choice2";
29 private static final String CHOICE3 = "choice3";
30 private static final String CHOICE4 = "choice4";
31 private static final String ANSWER = "answer";
32
33 // All fields used in user table
34 private static final String KEY_ID_USERS = "id";
35 private static final String USER_NAME = "name";
36 private static final String USER_SCORE = "score";
37
38 // Question Table Create Query in this string
39 private static final String CREATE_TABLE_QUESTION = "CREATE TABLE "
40 + TABLE_QUESTION + "(" + KEY_ID_QUESTION
41 + " INTEGER PRIMARY KEY AUTOINCREMENT," + QUESTION + " TEXT,"
42 + CHOICE1 + " TEXT, " + CHOICE2 + " TEXT, " + CHOICE3 + " TEXT, "
43 + CHOICE4 + " TEXT, " + ANSWER + " TEXT);";
44
45 // User Table Query
46 private static final String CREATE_TABLE_USER = "CREATE TABLE " + TABLE_USER + "(" + KEY_ID_USERS
47 + " INTEGER PRIMARY KEY AUTOINCREMENT," + USER_NAME + " TEXT, " + USER_SCORE + " INTEGER);";
48
49 public MyDataBaseHelper(Context context) {
50 super(context, DATABASE_QUESTION, null, DATABASE_VERSION);
51 }
52
53
54 /**
55 * This method is called by system if the database is accessed but not yet
56 * created.
57 */
58 @Override
59 public void onCreate(SQLiteDatabase db) {
60 Log.d("DBHelper", "Created db");
61 Log.d("DBHelper", CREATE_TABLE_QUESTION);
62 db.execSQL(CREATE_TABLE_QUESTION); // create question table
63 db.execSQL(CREATE_TABLE_USER);
64 }
65
66 /**
67 * This method is called when any modifications in database are done like
68 * version is updated or database schema is changed
69 */
70 @Override
71 public void onUpgrade(SQLiteDatabase db, int oldvers, int newvers) {
72 db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTION);
73 db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
74 onCreate(db);
75 }
76
77 /**
78 * This method is used to add question detail in question Table
79 */
80 public long addInitialQuestion (Question question) {
81 SQLiteDatabase db = this.getWritableDatabase();
82 // Creating content values
83 ContentValues values = new ContentValues();
84 values.put(QUESTION, question.getQuestion());
85 values.put(CHOICE1, question.getChoice(0));
86 values.put(CHOICE2, question.getChoice(1));
87 values.put(CHOICE3, question.getChoice(2));
88 values.put(CHOICE4, question.getChoice(3));
89 values.put(ANSWER, question.getAnswer());
90 // insert row in question table
91 long insert = db.insert(TABLE_QUESTION, null, values);
92 return insert;
93 }
94
95 /**
96 * To extract data from database and save it Arraylist of data type
97 * Question
98 */
99 public List<Question> getAllQuestionsList() {
100 List<Question> questionArrayList = new ArrayList<>();
101 String selectQuery = "SELECT * FROM " + TABLE_QUESTION;
102
103 SQLiteDatabase db = this.getReadableDatabase();
104 Cursor c = db.rawQuery(selectQuery, null);
105
106 // looping through all records and adding to the list
107 if (c.moveToFirst()) {
108 do {
109 Question question = new Question();
110
111 String questText= c.getString(c.getColumnIndex(QUESTION));
112 question.setQuestion(questText);
113
114 String choice1Text= c.getString(c.getColumnIndex(CHOICE1));
115 question.setChoice(0,choice1Text);
116
117 String choice2Text= c.getString(c.getColumnIndex(CHOICE2));
118 question.setChoice(1,choice2Text);
119
120 String choice3Text= c.getString(c.getColumnIndex(CHOICE3));
121 question.setChoice(2,choice3Text);
122
123 String choice4Text= c.getString(c.getColumnIndex(CHOICE4));
124 question.setChoice(3,choice4Text);
125
126 String answerText= c.getString(c.getColumnIndex(ANSWER));
127 question.setAnswer(answerText);
128
129 // adding to Questions list
130 questionArrayList.add(question);
131 } while (c.moveToNext());
132 Collections.shuffle(questionArrayList);
133 }
134 return questionArrayList;
135 }
136
137 public List<User> getAllUser(){
138 String sortOrder = "SELECT * FROM " + TABLE_USER + " ORDER BY " + USER_SCORE + " DESC";
139 List<User> userList = new ArrayList<User>();
140
141 SQLiteDatabase db = this.getReadableDatabase();
142 Cursor c = db.rawQuery(sortOrder, null);
143 if(c.moveToFirst()){
144 User user = new User();
145 }
146 return userList;
147 }
148
149 public void addUser(User user) {
150 SQLiteDatabase db = this.getWritableDatabase();
151 ContentValues values = new ContentValues();
152 values.put(USER_NAME, user.getName());
153 // Inserting Row
154 db.insert(TABLE_USER, USER_NAME, values);
155 db.close();
156
157 }
158
159 public void updateUser(User user) {
160 SQLiteDatabase db = this.getWritableDatabase();
161
162 ContentValues values = new ContentValues();
163 values.put(USER_NAME, user.getName());
164 // updating row
165 db.update(TABLE_USER, values, USER_NAME + " = ?",
166 new String[]{String.valueOf(user.getId())});
167 db.close();
168 }
169
170 public void deleteUser(User user) {
171 SQLiteDatabase db = this.getWritableDatabase();
172 // delete user record by id
173 db.delete(TABLE_USER, USER_NAME + " = ?",
174 new String[]{String.valueOf(user.getId())});
175 db.delete(TABLE_USER, USER_SCORE + " = ?",
176 new String[]{String.valueOf(user.getId())});
177 db.close();
178 }
179
180 public boolean hasUser(String user){
181
182 String searchQuery = "SELECT * FROM " + TABLE_USER + " WHERE " + USER_NAME + " = '" + user + "'";
183
184 SQLiteDatabase db = this.getReadableDatabase();
185 Cursor c = db.rawQuery(searchQuery, null);
186 c.moveToFirst();
187
188 if (c.getCount() > 0) {
189 c.close();
190 db.close();
191 return true;
192 } else {
193 c.close();
194 db.close();
195 return false;
196 }
197 }
198
199 public void addScore(int point){
200 SQLiteDatabase db = this.getWritableDatabase();
201 ContentValues values = new ContentValues();
202 values.put(USER_SCORE, point);
203 // Inserting Row
204 db.update(TABLE_USER, values,null , null);
205 db.close();
206 }
207
208}
209
210import android.content.Intent;
211import android.support.v7.app.AppCompatActivity;
212import android.os.Bundle;
213import android.util.Log;
214import android.view.View;
215import android.widget.Button;
216import android.widget.TextView;
217import android.widget.Toast;
218
219import java.util.List;
220
221public class QuizActivity extends AppCompatActivity {
222
223 private QuestionBank mQuestionLibrary = new QuestionBank();
224
225 private TextView mScoreView; // view for current total score
226 private TextView mQuestionView; //current question to answer
227 private Button mButtonChoice1; // multiple choice 1 for mQuestionView
228 private Button mButtonChoice2; // multiple choice 2 for mQuestionView
229 private Button mButtonChoice3; // multiple choice 3 for mQuestionView
230 private Button mButtonChoice4; // multiple choice 4 for mQuestionView
231
232 private String mAnswer; // correct answer for question in mQuestionView
233 private int mScore = 0; // current total score
234 private int mQuestionNumber = 0; // current question number
235
236 private String username = "";
237
238 MyDataBaseHelper myDataBaseHelper;
239
240 private static final String KEY_QUESTION_NUMBER = "questionNumber";
241 private static final String KEY_SCORE = "currentScore";
242
243
244 @Override
245 protected void onCreate(Bundle savedInstanceState) {
246 super.onCreate(savedInstanceState);
247 setContentView(R.layout.activity_quiz);
248 // setup screen for the first question with four alternative to answer
249 mScoreView = (TextView)findViewById(R.id.score);
250 mQuestionView = (TextView)findViewById(R.id.question);
251 mButtonChoice1 = (Button)findViewById(R.id.choice1);
252 mButtonChoice2 = (Button)findViewById(R.id.choice2);
253 mButtonChoice3 = (Button)findViewById(R.id.choice3);
254 mButtonChoice4 = (Button)findViewById(R.id.choice4);
255
256
257 Intent intent = getIntent();
258 username = intent.getStringExtra("username");
259
260 myDataBaseHelper = new MyDataBaseHelper(this);
261
262 mQuestionLibrary.initQuestions(getApplicationContext());
263
264 if(savedInstanceState != null){
265 mScore = savedInstanceState.getInt(KEY_SCORE,0);
266 mQuestionNumber = savedInstanceState.getInt(KEY_QUESTION_NUMBER, 0) - 1;
267 }
268
269 updateQuestion();
270 // show current total score for the user
271 updateScore(mScore);
272 }
273
274 private void updateQuestion(){
275 // check if we are not outside array bounds for questions
276 if(mQuestionNumber<mQuestionLibrary.getLength() ){
277 // set the text for new question,
278 // and new 4 alternative to answer on four buttons
279 mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
280 mButtonChoice1.setText(mQuestionLibrary.getChoice(mQuestionNumber, 1));
281 mButtonChoice2.setText(mQuestionLibrary.getChoice(mQuestionNumber, 2));
282 mButtonChoice3.setText(mQuestionLibrary.getChoice(mQuestionNumber, 3));
283 mButtonChoice4.setText(mQuestionLibrary.getChoice(mQuestionNumber,4));
284 mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
285 mQuestionNumber++;
286 }
287 else {
288 Toast.makeText(QuizActivity.this, "It was the last question!", Toast.LENGTH_SHORT).show();
289 Intent intent = new Intent(QuizActivity.this, HighScoreActivity.class);
290 intent.putExtra("score", mScore); // pass the current score to the second screen
291 intent.putExtra("username", username);
292 myDataBaseHelper.addScore(mScore);
293 startActivity(intent);
294 }
295 }
296
297 // show current total score for the user
298 private void updateScore(int point) {
299 mScoreView.setText(""+mScore+"/"+mQuestionLibrary.getLength());
300 }
301
302 public void onClick(View view) {
303 //all logic for all answers buttons in one method
304 Button answer = (Button) view;
305 // if the answer is correct, increase the score
306 if (answer.getText().equals(mAnswer)){
307 mScore = mScore + 1;
308 Toast.makeText(QuizActivity.this, "Correct!", Toast.LENGTH_SHORT).show();
309 }else
310 Toast.makeText(QuizActivity.this, "Wrong!", Toast.LENGTH_SHORT).show();
311 // show current total score for the user
312 updateScore(mScore);
313 // once user answer the question, we move on to the next one, if any
314 updateQuestion();
315 }
316
317 @Override
318 protected void onResume() {
319 super.onResume();
320 /*
321 MyDataBaseHelper dataBaseHelper = new MyDataBaseHelper((this));
322 List<Question> questions = dataBaseHelper.getAllQuestionsList();
323 if(questions.isEmpty())
324 {
325 Log.d("QuizActivity", "List is empty");
326 } dataBaseHelper.addInitialQuestion(new Question("1. When did Google acquire Android ?",
327 new String[]{"2001", "2003", "2004", "2005"}, "2005"));
328 */
329 }
330
331 @Override
332 protected void onSaveInstanceState(Bundle savedInstanceState) {
333 super.onSaveInstanceState(savedInstanceState);
334 savedInstanceState.putInt(KEY_SCORE, mScore);
335 savedInstanceState.putInt(KEY_QUESTION_NUMBER, mQuestionNumber);
336 }
337
338 @Override
339 protected void onRestoreInstanceState(Bundle savedInstanceState) {
340 super.onRestoreInstanceState(savedInstanceState);
341 mScore = savedInstanceState.getInt(KEY_SCORE,0);
342 mQuestionNumber = savedInstanceState.getInt(KEY_QUESTION_NUMBER, 0);
343 }
344}
345
346import android.content.Intent;
347import android.content.SharedPreferences;
348import android.support.v7.app.AppCompatActivity;
349import android.os.Bundle;
350import android.view.View;
351import android.widget.Button;
352import android.widget.TextView;
353
354public class HighScoreActivity extends AppCompatActivity {
355
356 private String username;
357 private TextView txtScore;
358 private TextView txtHighScore;
359
360 @Override
361 protected void onCreate(Bundle savedInstanceState) {
362 super.onCreate(savedInstanceState);
363 setContentView(R.layout.activity_highest_score);
364
365 txtScore = (TextView) findViewById(R.id.textScore);
366 txtHighScore = (TextView) findViewById(R.id.textHighScore);
367
368 Intent intent = getIntent();
369 int score = intent.getIntExtra("score",0);
370 username = intent.getStringExtra("username");
371
372 txtScore.setText(username + "'s Score: " + score);
373//
374// SharedPreferences mypref = getPreferences(MODE_PRIVATE);
375// int highscore = mypref.getInt("highscore", 0);
376// if (highscore >= score){
377// txtHighScore.setText("High Score: " + highscore);
378// }
379// else {
380// txtHighScore.setText("New High Score: " + score);
381// SharedPreferences.Editor editor = mypref.edit();
382// editor.putInt("highscore", score);
383// editor.commit();
384// }
385
386 }
387
388 public void onClick(View view) {
389 Intent intent = new Intent(HighScoreActivity.this, QuizActivity.class);
390 intent.putExtra("username", username);
391 startActivity(intent);
392
393 }
394
395 public void logOutOnClick(View view) {
396
397 Intent intent = new Intent(HighScoreActivity.this, LoginActivity.class);
398 startActivity(intent);
399 finish();
400
401 }
402}