Skip to content

Most visited

Recently visited

navigation
Quiz / Application / src / com.example.android.wearable.quiz /

MainActivity.java

1
/*
2
 * Copyright (C) 2014 The Android Open Source Project
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
 
17
package com.example.android.wearable.quiz;
18
 
19
import static com.example.android.wearable.quiz.Constants.ANSWERS;
20
import static com.example.android.wearable.quiz.Constants.CHOSEN_ANSWER_CORRECT;
21
import static com.example.android.wearable.quiz.Constants.CORRECT_ANSWER_INDEX;
22
import static com.example.android.wearable.quiz.Constants.NUM_CORRECT;
23
import static com.example.android.wearable.quiz.Constants.NUM_INCORRECT;
24
import static com.example.android.wearable.quiz.Constants.NUM_SKIPPED;
25
import static com.example.android.wearable.quiz.Constants.QUESTION;
26
import static com.example.android.wearable.quiz.Constants.QUESTION_INDEX;
27
import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_ANSWERED;
28
import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_DELETED;
29
import static com.example.android.wearable.quiz.Constants.QUIZ_ENDED_PATH;
30
import static com.example.android.wearable.quiz.Constants.QUIZ_EXITED_PATH;
31
import static com.example.android.wearable.quiz.Constants.RESET_QUIZ_PATH;
32
 
33
import android.app.Activity;
34
import android.graphics.Color;
35
import android.net.Uri;
36
import android.os.Bundle;
37
import android.util.Log;
38
import android.view.LayoutInflater;
39
import android.view.View;
40
import android.widget.Button;
41
import android.widget.EditText;
42
import android.widget.LinearLayout;
43
import android.widget.RadioGroup;
44
import android.widget.TextView;
45
 
46
import com.google.android.gms.common.ConnectionResult;
47
import com.google.android.gms.common.api.GoogleApiClient;
48
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
49
import com.google.android.gms.common.api.ResultCallback;
50
import com.google.android.gms.common.data.FreezableUtils;
51
import com.google.android.gms.wearable.DataApi;
52
import com.google.android.gms.wearable.DataEvent;
53
import com.google.android.gms.wearable.DataEventBuffer;
54
import com.google.android.gms.wearable.DataItem;
55
import com.google.android.gms.wearable.DataItemBuffer;
56
import com.google.android.gms.wearable.DataMap;
57
import com.google.android.gms.wearable.DataMapItem;
58
import com.google.android.gms.wearable.MessageApi;
59
import com.google.android.gms.wearable.MessageEvent;
60
import com.google.android.gms.wearable.Node;
61
import com.google.android.gms.wearable.NodeApi;
62
import com.google.android.gms.wearable.PutDataMapRequest;
63
import com.google.android.gms.wearable.PutDataRequest;
64
import com.google.android.gms.wearable.Wearable;
65
 
66
import org.json.JSONArray;
67
import org.json.JSONException;
68
import org.json.JSONObject;
69
 
70
import java.io.IOException;
71
import java.util.ArrayList;
72
import java.util.Collections;
73
import java.util.HashMap;
74
import java.util.List;
75
import java.util.Map;
76
import java.util.PriorityQueue;
77
 
78
/**
79
 * Allows the user to create questions, which will be put as notifications on the watch's stream.
80
 * The status of questions will be updated on the phone when the user answers them.
81
 */
82
public class MainActivity extends Activity implements DataApi.DataListener,
83
        MessageApi.MessageListener, ConnectionCallbacks,
84
        GoogleApiClient.OnConnectionFailedListener {
85
 
86
    private static final String TAG = "ExampleQuizApp";
87
    private static final String QUIZ_JSON_FILE = "Quiz.json";
88
 
89
    // Various UI components.
90
    private EditText questionEditText;
91
    private EditText choiceAEditText;
92
    private EditText choiceBEditText;
93
    private EditText choiceCEditText;
94
    private EditText choiceDEditText;
95
    private RadioGroup choicesRadioGroup;
96
    private TextView quizStatus;
97
    private LinearLayout quizButtons;
98
    private LinearLayout questionsContainer;
99
    private Button readQuizFromFileButton;
100
    private Button resetQuizButton;
101
 
102
    private GoogleApiClient mGoogleApiClient;
103
    private PriorityQueue<Question> mFutureQuestions;
104
    private int mQuestionIndex = 0;
105
    private boolean mHasQuestionBeenAsked = false;
106
 
107
    // Data to display in end report.
108
    private int mNumCorrect = 0;
109
    private int mNumIncorrect = 0;
110
    private int mNumSkipped = 0;
111
 
112
    private static final Map<Integer, Integer> radioIdToIndex;
113
 
114
    static {
115
        Map<Integer, Integer> temp = new HashMap<Integer, Integer>(4);
116
        temp.put(R.id.choice_a_radio, 0);
117
        temp.put(R.id.choice_b_radio, 1);
118
        temp.put(R.id.choice_c_radio, 2);
119
        temp.put(R.id.choice_d_radio, 3);
120
        radioIdToIndex = Collections.unmodifiableMap(temp);
121
    }
122
 
123
    @Override
124
    protected void onCreate(Bundle savedInstanceState) {
125
        super.onCreate(savedInstanceState);
126
        setContentView(R.layout.main);
127
 
128
        mGoogleApiClient = new GoogleApiClient.Builder(this)
129
                .addApi(Wearable.API)
130
                .addConnectionCallbacks(this)
131
                .addOnConnectionFailedListener(this)
132
                .build();
133
        mFutureQuestions = new PriorityQueue<Question>(10);
134
 
135
        // Find UI components to be used later.
136
        questionEditText = (EditText) findViewById(R.id.question_text);
137
        choiceAEditText = (EditText) findViewById(R.id.choice_a_text);
138
        choiceBEditText = (EditText) findViewById(R.id.choice_b_text);
139
        choiceCEditText = (EditText) findViewById(R.id.choice_c_text);
140
        choiceDEditText = (EditText) findViewById(R.id.choice_d_text);
141
        choicesRadioGroup = (RadioGroup) findViewById(R.id.choices_radio_group);
142
        quizStatus = (TextView) findViewById(R.id.quiz_status);
143
        quizButtons = (LinearLayout) findViewById(R.id.quiz_buttons);
144
        questionsContainer = (LinearLayout) findViewById(R.id.questions_container);
145
        readQuizFromFileButton = (Button) findViewById(R.id.read_quiz_from_file_button);
146
        resetQuizButton = (Button) findViewById(R.id.reset_quiz_button);
147
    }
148
 
149
    @Override
150
    protected void onStart() {
151
        super.onStart();
152
        if (!mGoogleApiClient.isConnected()) {
153
            mGoogleApiClient.connect();
154
        }
155
    }
156
 
157
    @Override
158
    protected void onStop() {
159
        Wearable.DataApi.removeListener(mGoogleApiClient, this);
160
        Wearable.MessageApi.removeListener(mGoogleApiClient, this);
161
 
162
        // Tell the wearable to end the quiz (counting unanswered questions as skipped), and then
163
        // disconnect mGoogleApiClient.
164
        DataMap dataMap = new DataMap();
165
        dataMap.putInt(NUM_CORRECT, mNumCorrect);
166
        dataMap.putInt(NUM_INCORRECT, mNumIncorrect);
167
        if (mHasQuestionBeenAsked) {
168
            mNumSkipped += 1;
169
        }
170
        mNumSkipped += mFutureQuestions.size();
171
        dataMap.putInt(NUM_SKIPPED, mNumSkipped);
172
        if (mNumCorrect + mNumIncorrect + mNumSkipped > 0) {
173
            sendMessageToWearable(QUIZ_EXITED_PATH, dataMap.toByteArray());
174
        }
175
 
176
        clearQuizStatus();
177
        super.onStop();
178
    }
179
 
180
    @Override
181
    public void onConnected(Bundle connectionHint) {
182
        Wearable.DataApi.addListener(mGoogleApiClient, this);
183
        Wearable.MessageApi.addListener(mGoogleApiClient, this);
184
    }
185
 
186
    @Override
187
    public void onConnectionSuspended(int cause) {
188
        // Ignore
189
    }
190
 
191
    @Override
192
    public void onConnectionFailed(ConnectionResult result) {
193
        Log.e(TAG, "Failed to connect to Google Play Services");
194
    }
195
 
196
    @Override
197
    public void onMessageReceived(MessageEvent messageEvent) {
198
        if (messageEvent.getPath().equals(RESET_QUIZ_PATH)) {
199
            runOnUiThread(new Runnable() {
200
                @Override
201
                public void run() {
202
                    resetQuiz(null);
203
                }
204
            });
205
        }
206
    }
207
 
208
    /**
209
     * Used to ensure questions with smaller indexes come before questions with larger
210
     * indexes. For example, question0 should come before question1.
211
     */
212
    private static class Question implements Comparable<Question> {
213
 
214
        private String question;
215
        private int questionIndex;
216
        private String[] answers;
217
        private int correctAnswerIndex;
218
 
219
        public Question(String question, int questionIndex, String[] answers,
220
                int correctAnswerIndex) {
221
            this.question = question;
222
            this.questionIndex = questionIndex;
223
            this.answers = answers;
224
            this.correctAnswerIndex = correctAnswerIndex;
225
        }
226
 
227
        public static Question fromJson(JSONObject questionObject, int questionIndex)
228
                throws JSONException {
229
            String question = questionObject.getString(JsonUtils.JSON_FIELD_QUESTION);
230
            JSONArray answersJsonArray = questionObject.getJSONArray(JsonUtils.JSON_FIELD_ANSWERS);
231
            String[] answers = new String[JsonUtils.NUM_ANSWER_CHOICES];
232
            for (int j = 0; j < answersJsonArray.length(); j++) {
233
                answers[j] = answersJsonArray.getString(j);
234
            }
235
            int correctIndex = questionObject.getInt(JsonUtils.JSON_FIELD_CORRECT_INDEX);
236
            return new Question(question, questionIndex, answers, correctIndex);
237
        }
238
 
239
        @Override
240
        public int compareTo(Question that) {
241
            return this.questionIndex - that.questionIndex;
242
        }
243
 
244
        public PutDataRequest toPutDataRequest() {
245
            PutDataMapRequest request = PutDataMapRequest.create("/question/" + questionIndex);
246
            DataMap dataMap = request.getDataMap();
247
            dataMap.putString(QUESTION, question);
248
            dataMap.putInt(QUESTION_INDEX, questionIndex);
249
            dataMap.putStringArray(ANSWERS, answers);
250
            dataMap.putInt(CORRECT_ANSWER_INDEX, correctAnswerIndex);
251
            PutDataRequest putDataRequest = request.asPutDataRequest();
252
            putDataRequest.setUrgent();
253
            return putDataRequest;
254
        }
255
    }
256
 
257
    /**
258
     * Create a quiz, as defined in Quiz.json, when the user clicks on "Read quiz from file."
259
     *
260
     * @throws IOException
261
     */
262
    public void readQuizFromFile(View view) throws IOException, JSONException {
263
        clearQuizStatus();
264
        JSONObject jsonObject = JsonUtils.loadJsonFile(this, QUIZ_JSON_FILE);
265
        JSONArray jsonArray = jsonObject.getJSONArray(JsonUtils.JSON_FIELD_QUESTIONS);
266
        for (int i = 0; i < jsonArray.length(); i++) {
267
            JSONObject questionObject = jsonArray.getJSONObject(i);
268
            Question question = Question.fromJson(questionObject, mQuestionIndex++);
269
            addQuestionDataItem(question);
270
            setNewQuestionStatus(question.question);
271
        }
272
    }
273
 
274
    /**
275
     * Adds a question (with answer choices) when user clicks on "Add Question."
276
     */
277
    public void addQuestion(View view) {
278
        // Retrieve the question and answers supplied by the user.
279
        String question = questionEditText.getText().toString();
280
        String[] answers = new String[4];
281
        answers[0] = choiceAEditText.getText().toString();
282
        answers[1] = choiceBEditText.getText().toString();
283
        answers[2] = choiceCEditText.getText().toString();
284
        answers[3] = choiceDEditText.getText().toString();
285
        int correctAnswerIndex = radioIdToIndex.get(choicesRadioGroup.getCheckedRadioButtonId());
286
 
287
        addQuestionDataItem(new Question(question, mQuestionIndex++, answers, correctAnswerIndex));
288
        setNewQuestionStatus(question);
289
 
290
        // Clear the edit boxes to let the user input a new question.
291
        questionEditText.setText("");
292
        choiceAEditText.setText("");
293
        choiceBEditText.setText("");
294
        choiceCEditText.setText("");
295
        choiceDEditText.setText("");
296
    }
297
 
298
    /**
299
     * Adds the questions (and answers) to the wearable's stream by creating a Data Item
300
     * that will be received on the wearable, which will create corresponding notifications.
301
     */
302
    private void addQuestionDataItem(Question question) {
303
        if (!mHasQuestionBeenAsked) {
304
            // Ask the question now.
305
            Wearable.DataApi.putDataItem(mGoogleApiClient, question.toPutDataRequest());
306
            setHasQuestionBeenAsked(true);
307
        } else {
308
            // Enqueue the question to be asked in the future.
309
            mFutureQuestions.add(question);
310
        }
311
    }
312
 
313
    /**
314
     * Sets the question's status to be the default "unanswered." This will be updated when the
315
     * user chooses an answer for the question on the wearable.
316
     */
317
    private void setNewQuestionStatus(String question) {