-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathQuizActivity.java
More file actions
301 lines (250 loc) · 10.9 KB
/
QuizActivity.java
File metadata and controls
301 lines (250 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.classicalmusicquiz;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
public class QuizActivity extends AppCompatActivity implements View.OnClickListener, ExoPlayer.EventListener {
private static final int CORRECT_ANSWER_DELAY_MILLIS = 1000;
private static final String REMAINING_SONGS_KEY = "remaining_songs";
private static final String TAG = QuizActivity.class.getSimpleName();
private int[] mButtonIDs = {R.id.buttonA, R.id.buttonB, R.id.buttonC, R.id.buttonD};
private ArrayList<Integer> mRemainingSampleIDs;
private ArrayList<Integer> mQuestionSampleIDs;
private int mAnswerSampleID;
private int mCurrentScore;
private int mHighScore;
private Button[] mButtons;
private SimpleExoPlayer mExoPlayer;
private SimpleExoPlayerView mPlayerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
// Initialize the player view.
mPlayerView = (SimpleExoPlayerView) findViewById(R.id.playerView);
boolean isNewGame = !getIntent().hasExtra(REMAINING_SONGS_KEY);
// If it's a new game, set the current score to 0 and load all samples.
if (isNewGame) {
QuizUtils.setCurrentScore(this, 0);
mRemainingSampleIDs = Sample.getAllSampleIDs(this);
// Otherwise, get the remaining songs from the Intent.
} else {
mRemainingSampleIDs = getIntent().getIntegerArrayListExtra(REMAINING_SONGS_KEY);
}
// Get current and high scores.
mCurrentScore = QuizUtils.getCurrentScore(this);
mHighScore = QuizUtils.getHighScore(this);
// Generate a question and get the correct answer.
mQuestionSampleIDs = QuizUtils.generateQuestion(mRemainingSampleIDs);
mAnswerSampleID = QuizUtils.getCorrectAnswerID(mQuestionSampleIDs);
// Load the question mark as the background image until the user answers the question.
mPlayerView.setDefaultArtwork(BitmapFactory.decodeResource
(getResources(), R.drawable.question_mark));
// If there is only one answer left, end the game.
if (mQuestionSampleIDs.size() < 2) {
QuizUtils.endGame(this);
finish();
}
// Initialize the buttons with the composers names.
mButtons = initializeButtons(mQuestionSampleIDs);
Sample answerSample = Sample.getSampleByID(this, mAnswerSampleID);
if (answerSample == null) {
Toast.makeText(this, getString(R.string.sample_not_found_error),
Toast.LENGTH_SHORT).show();
return;
}
// Initialize the player.
initializePlayer(Uri.parse(answerSample.getUri()));
}
/**
* Initializes the button to the correct views, and sets the text to the composers names,
* and set's the OnClick listener to the buttons.
*
* @param answerSampleIDs The IDs of the possible answers to the question.
* @return The Array of initialized buttons.
*/
private Button[] initializeButtons(ArrayList<Integer> answerSampleIDs) {
Button[] buttons = new Button[mButtonIDs.length];
for (int i = 0; i < answerSampleIDs.size(); i++) {
Button currentButton = (Button) findViewById(mButtonIDs[i]);
Sample currentSample = Sample.getSampleByID(this, answerSampleIDs.get(i));
buttons[i] = currentButton;
currentButton.setOnClickListener(this);
if (currentSample != null) {
currentButton.setText(currentSample.getComposer());
}
}
return buttons;
}
/**
* Initialize ExoPlayer.
* @param mediaUri The URI of the sample to play.
*/
private void initializePlayer(Uri mediaUri) {
if (mExoPlayer == null) {
// Create an instance of the ExoPlayer.
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
mPlayerView.setPlayer(mExoPlayer);
// Set the ExoPlayer.EventListener to this activity.
mExoPlayer.addListener(this);
// Prepare the MediaSource.
String userAgent = Util.getUserAgent(this, "ClassicalMusicQuiz");
MediaSource mediaSource = new ExtractorMediaSource(mediaUri, new DefaultDataSourceFactory(
this, userAgent), new DefaultExtractorsFactory(), null, null);
mExoPlayer.prepare(mediaSource);
mExoPlayer.setPlayWhenReady(true);
}
}
/**
* Release ExoPlayer.
*/
private void releasePlayer() {
mExoPlayer.stop();
mExoPlayer.release();
mExoPlayer = null;
}
/**
* The OnClick method for all of the answer buttons. The method uses the index of the button
* in button array to to get the ID of the sample from the array of question IDs. It also
* toggles the UI to show the correct answer.
*
* @param v The button that was clicked.
*/
@Override
public void onClick(View v) {
// Show the correct answer.
showCorrectAnswer();
// Get the button that was pressed.
Button pressedButton = (Button) v;
// Get the index of the pressed button
int userAnswerIndex = -1;
for (int i = 0; i < mButtons.length; i++) {
if (pressedButton.getId() == mButtonIDs[i]) {
userAnswerIndex = i;
}
}
// Get the ID of the sample that the user selected.
int userAnswerSampleID = mQuestionSampleIDs.get(userAnswerIndex);
// If the user is correct, increase there score and update high score.
if (QuizUtils.userCorrect(mAnswerSampleID, userAnswerSampleID)) {
mCurrentScore++;
QuizUtils.setCurrentScore(this, mCurrentScore);
if (mCurrentScore > mHighScore) {
mHighScore = mCurrentScore;
QuizUtils.setHighScore(this, mHighScore);
}
}
// Remove the answer sample from the list of all samples, so it doesn't get asked again.
mRemainingSampleIDs.remove(Integer.valueOf(mAnswerSampleID));
// Wait some time so the user can see the correct answer, then go to the next question.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mExoPlayer.stop();
Intent nextQuestionIntent = new Intent(QuizActivity.this, QuizActivity.class);
nextQuestionIntent.putExtra(REMAINING_SONGS_KEY, mRemainingSampleIDs);
finish();
startActivity(nextQuestionIntent);
}
}, CORRECT_ANSWER_DELAY_MILLIS);
}
/**
* Disables the buttons and changes the background colors and player art to
* show the correct answer.
*/
private void showCorrectAnswer() {
mPlayerView.setDefaultArtwork(Sample.getComposerArtBySampleID(this, mAnswerSampleID));
for (int i = 0; i < mQuestionSampleIDs.size(); i++) {
int buttonSampleID = mQuestionSampleIDs.get(i);
mButtons[i].setEnabled(false);
if (buttonSampleID == mAnswerSampleID) {
mButtons[i].getBackground().setColorFilter(ContextCompat.getColor
(this, android.R.color.holo_green_light),
PorterDuff.Mode.MULTIPLY);
mButtons[i].setTextColor(Color.WHITE);
} else {
mButtons[i].getBackground().setColorFilter(ContextCompat.getColor
(this, android.R.color.holo_red_light),
PorterDuff.Mode.MULTIPLY);
mButtons[i].setTextColor(Color.WHITE);
}
}
}
/**
* Release the player when the activity is destroyed.
*/
@Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
}
// ExoPlayer Event Listeners
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if((playbackState == ExoPlayer.STATE_READY) && playWhenReady){
Log.d(TAG, "onPlayerStateChanged: PLAYING");
} else if((playbackState == ExoPlayer.STATE_READY)){
Log.d(TAG, "onPlayerStateChanged: PAUSED");
}
}
@Override
public void onPlayerError(ExoPlaybackException error) {
}
@Override
public void onPositionDiscontinuity() {
}
}