I'm making a quiz app with question about different countries. I already made it work for one country, but now I'd like to make it work for all the countries, but I don't exactly know how. I've made a question library and a quizactivity, but I don't know how to proceed right now, so I hope someone can help me.
Here is my quizactivity:
package com.example.quizapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private Button mButtonChoice4;
private String mAnswerFrankrijk;
private int mScoreFrankrijk = 0;
private int mQuestionNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mScoreView = (TextView)findViewById(R.id.score1);
mQuestionView = (TextView)findViewById(R.id.question1);
mButtonChoice1 = (Button)findViewById(R.id.choice1);
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice3 = (Button)findViewById(R.id.choice3);
mButtonChoice4 = (Button)findViewById(R.id.choice4);
updateQuestion();
//Start of Button Listener for Button1
mButtonChoice1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice1.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button1
//Start of Button Listener for Button2
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button2
//Start of Button Listener for Button3
mButtonChoice3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice3.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button3
//Start of Button Listener for Button3
mButtonChoice4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice4.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optional
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button3
}
private void updateQuestion(){
mQuestionView.setText(mQuestionLibrary.getQuestionFrankrijk(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1Frankrijk(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2Frankrijk(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3Frankrijk(mQuestionNumber));
mButtonChoice4.setText(mQuestionLibrary.getChoice4Frankrijk(mQuestionNumber));
mAnswerFrankrijk = mQuestionLibrary.getCorrectAnswerFrankrijk(mQuestionNumber);
mQuestionNumber++;
}
private void updateScore(int point) {mScoreView.setText("" + mScoreFrankrijk);
}
}
And here is my question library:
package com.example.quizapp;
public class QuestionLibrary {
private String mQuestionsFrankrijk [] = {
"Wat is de hoofdstad van Frankrijk?",
"Wat is de bijnaam van het Franse nationale voetbalelftal",
"Welke van de volgende landen grenst niet aan Frankrijk?",
"Bij welke sport hoort 'le maillot jaune'?",
"Welk museum in Parijs heeft een piramide als ingang?"
};
private String mChoicesFrankrijk [][] = {
{"Lyon", "Parijs", "Nice", "Bordeaux"},
{"La France", "Le Coq Sportif", "Les Bleus", "Les Gagnants"},
{"Zwitserland", "België", "Spanje", "Oostenrijk"},
{"Tennis", "Wielrennen", "Rugby", "Cricket"},
{"Musée d'Orsay", "Musée Rodin", "Louvre", "Centre Georges Pompidou"},
};
private String mCorrectAnswers [] = {"Parijs", "Les Bleus", "Oostenrijk", "Wielrennen", "Louvre"};
public String getQuestionFrankrijk(int a) {
String question = mQuestionsFrankrijk[a];
return question;
}
public String getChoice1Frankrijk(int a) {
String choice0 = mChoicesFrankrijk[a][0];
return choice0;
}
public String getChoice2Frankrijk(int a) {
String choice1 = mChoicesFrankrijk[a][1];
return choice1;
}
public String getChoice3Frankrijk(int a) {
String choice2 = mChoicesFrankrijk[a][2];
return choice2;
}
public String getChoice4Frankrijk(int a) {
String choice3 = mChoicesFrankrijk[a][3];
return choice3;
}
public String getCorrectAnswerFrankrijk(int a) {
String answer = mCorrectAnswers[a];
return answer;
}
}
The easiest solution I can think is to make QuestionLibrary an interface or abstract class. Then implement a Country1QuestionLibrary with a specific country's questions and Country2QuestionLibrary with another set of questions. Then you can dynamically swap out the set of questions being presented to the user by doing
questionLibrary = new Country1QuestionLibrary();
Then you need a way for your user to change the country. On the UI, add another button that's "Change Country" implemented similarly to how your other buttons are working. In the onClickListener, assign the other implementation of QuestionLibrary to the available questions and refresh the question and answers views.
As with most things programming, there are a bunch of ways to implement this. If you can implement the path I'm showing, take some time to try and come up with a different solution on your own after seeing the downfalls or restrictions of this solution.
Related
I tried to build my app, and this error message was produced.
Unexpected character '=' (code 61) (expected a name start character)
at [row,col {unknown-source}]: [41,21]
I have cleaned my code and tried to clean my code and inspected my code and i can't find anything wrong my code, and help would be gratefully recieved.
This is my MainActivity.
package com.michaeldoughty.android.football_quiz;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import
androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.*;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity
{
// to answer true for the question
private Button mTrueButton;
// to answer false for the question
private Button mFalseButton;
// to get the next question
private ImageButton mNextButton;
// to cheat
private Button mCheatButton;
// to hold the questions
private TextView mQuestionTextView;
// whether the user is a cheater
private boolean mIsCheater;
// a key used for the onSaveInstanceState
private final String KEY_INDEX = "index";
// An ActivityResultLauncher for the CheatActivity
ActivityResultLauncher<Intent> cheatActivityResultLauncher =
registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>()
{
#Override
public void onActivityResult (ActivityResult
result)
{
//checking if there is a result code from the
returned intent
if (result.getResultCode () == RESULT_OK)
{
// to check is there is any data in the
returned intent
if (result.getData() == null)
{
return;
}
// setting that the user is a cheater
mIsCheater = true;
}
}
});
// an array of Question objects
private Question [] mQuestionBank = new Question []
{
new Question (R.string.question_euro, true),
new Question (R.string.question_world_cup, false),
new Question (R.string.question_premier_league,
false),
new Question (R.string.question_england, true),
new Question (R.string.question_fa_cup, false),
new Question (R.string.question_league_cup, true)
};
// the index of the current question being displayed
private int mCurrentIndex = 0;
// to hold the percentage of correct answers
private double percentage = 0;
// to hold the amount of correct answers
private double correct = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// to check if there is a value of mCurrentIndex in the
savedInstanceState
if (savedInstanceState != null)
{
mCurrentIndex = savedInstanceState.getInt (KEY_INDEX,
0);
}
// to create the mQuestionTextView
mQuestionTextView = (TextView) findViewById
(R.id.question_text_view);
mQuestionTextView.setOnClickListener(new
View.OnClickListener()
{
#Override
public void onClick(View view)
{
// update the mCurrrentIndex
mCurrentIndex++;
// enable the mTrueButton and mFalseButton
mTrueButton.setEnabled (true);
mFalseButton.setEnabled (true);
if (mCurrentIndex < 6)
{
// call the updateQuestion method
updateQuestion();
}
else
{
displayPercentage ();
mCurrentIndex = 0;
updateQuestion();
}
}
});
// call the updateQuestion method
updateQuestion ();
// to create the mTrueButton
mTrueButton = (Button) findViewById (R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// call the checkAnswer method
checkAnswer (true);
// disable the mTrueButton and mFalseButton
mTrueButton.setEnabled (false);
mFalseButton.setEnabled (false);
}
});
// to create the mFalseButton
mFalseButton = (Button) findViewById (R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// call the checkAnswer method
checkAnswer (false);
// disable the mTrueButton and mFalseButton
mTrueButton.setEnabled (false);
mFalseButton.setEnabled (false);
}
});
// to create the mNextButton
mNextButton = (ImageButton) findViewById
(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// update the mCurrrentIndex
mCurrentIndex++;
// enable the mTrueButton and mFalseButton
mTrueButton.setEnabled (true);
mFalseButton.setEnabled (true);
if (mCurrentIndex < 6)
{
// call the updateQuestion method
updateQuestion();
}
else
{
displayPercentage ();
mCurrentIndex = 0;
updateQuestion();
}
}
});
// to create the mCheatButton
mCheatButton = (Button) findViewById (R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean answerIsTrue = mQuestionBank
[mCurrentIndex].isAnswerTrue ();
Intent intent = CheatActivity.newIntent
(MainActivity.this, answerIsTrue);
cheatActivityResultLauncher.launch (intent);
}
});
}
/**
The onSaveInstanceState method saves savedInstanceState when
the activity is stopped.
#param savedInstanceState, the bundle of the activity.
*/
#Override
public void onSaveInstanceState (Bundle savedInstanceState)
{
// call the super's constructor
super.onSaveInstanceState (savedInstanceState);
// to add the mCurrentIndex to the bundle
savedInstanceState.putInt (KEY_INDEX, mCurrentIndex);
}
/**
The updateQuestion method updates the question.
*/
public void updateQuestion ()
{
// get the next question
int question = mQuestionBank [mCurrentIndex].getTextResId
();
// to display the next question
mQuestionTextView.setText (question);
}
/**
The checkAnswer method checks the user's answer, to see if
its correct or not
#param userPressedTrue, the user's answer.
*/
public void checkAnswer (boolean userPressedTrue)
{
// getting the correct answer
boolean answerIsTrue = mQuestionBank
[mCurrentIndex].isAnswerTrue ();
// the message in the toast
int messageResId = 0;
// checking the user's answer and setting the right meassge
if (userPressedTrue == answerIsTrue)
{
messageResId = R.string.correct_toast;
correct++;
}
else
{
messageResId = R.string.incorrect_toast;
}
// displaying the meessage in a toast
Toast toast;
toast = Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT);
toast.setGravity (Gravity.TOP|Gravity.CENTER, 0, 0);
toast.show ();
}
/**
The displayPercentage displays the percentage of correct
answers the user had guessed.
*/
public void displayPercentage ()
{
// working out the percentage
percentage = (correct / mQuestionBank.length) * 100;
DecimalFormat df = new DecimalFormat("#.00");
// displaying the percentage as a toast
Toast.makeText(this, "You have guessed " +
df.format(percentage) + "%!", Toast.LENGTH_SHORT).show ();
// to set the correct and percentage back to zero
correct = 0;
percentage = 0;
}
}
Here is my CheatActivity
// an extra key for the intent which tells the CheatActivity
what the answer is
private static final String EXTRA_ANSWER_IS_TRUE =
"com.michaeldoughty.android.football_quiz_answer_is_true";
// an extra key for the intent which tells the MainActivity if
the user has cheated
private static final String EXTRA_ANSWER_IS_SHOWN =
"com.michaeldoughty.android.football_quiz_answer_shown";
// if the answer is true or not
private boolean mAnswerIsTrue;
// to hold the correct answer
private TextView mAnswerTextView;
// a button to show the correct answer
private Button mShowAnswerButton;
// to create an intent to create a CheatActivity
public static Intent newIntent (Context packageContext,
boolean answerIsTrue)
{
Intent intent = new Intent (packageContext,
CheatActivity.class);
intent.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return intent;
}
public static boolean wasAnswerShown (Intent result)
{
return result.getBooleanExtra (EXTRA_ANSWER_IS_SHOWN,
false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
// to get the mAnswerIsTrue
mAnswerIsTrue = getIntent ().getBooleanExtra
(EXTRA_ANSWER_IS_TRUE, false);
// to create the mAnswerTextView
mAnswerTextView = findViewById (R.id.answer_text_view);
// to create the mShowAnswerButton
mShowAnswerButton = findViewById (R.id.show_answer_button);
mShowAnswerButton.setOnClickListener(new
View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (mAnswerIsTrue)
{
mAnswerTextView.setText (R.string.true_button);
}
else
{
mAnswerTextView.setText
(R.string.false_button);
}
setAnswerShownResult (true);
}
});
}
/**
The setAnswerShownResult creates an Intent, to send the
isAnswerShown to the MainActivity.
#param isAnswerShown, whether the user has cheated or not.
*/
private void setAnswerShownResult (boolean isAnswerShown)
{
Intent data = new Intent ();
data.putExtra (EXTRA_ANSWER_IS_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
}
Here is my Question class
package com.michaeldoughty.android.football_quiz;
public class Question
{
// to hold the text res id of the question
private int mTextResId;
// to hold if the answer is true or false
private boolean mAnswerTrue;
/**
Constructor
*/
public Question (int textResId, boolean answerTrue)
{
mTextResId = textResId;
mAnswerTrue = answerTrue;
}
public int getTextResId()
{
return mTextResId;
}
public void setTextResId(int textResId)
{
mTextResId = textResId;
}
public boolean isAnswerTrue()
{
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue)
{
mAnswerTrue = answerTrue;
}
}
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.
What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?
Question Class
// This file contains questions from QuestionBank
class Question{
// array of questions
private String mQuestions [] = {
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// method returns number of questions
int getLength(){
return mQuestions.length;
}
// method returns question from array textQuestions[] based on array index
String getQuestion(int a) {
return mQuestions[a];
}
}
Main Activity.java
public class MainActivityextends AppCompatActivity {
private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
private int mQuestionNumber = 1; // current question number
//initialising navigation buttons
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
mQuestionText = (TextView) findViewById(R.id.txtQuestion);
// receive the current question number from last activity by Intent
Intent intent = getIntent();
currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking against total number of questions the user has attempted instead of total number of questions from Question Class
if (mQuestionNumber < currentQuestionNumber) {
updateQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// i want it to loop backwards from here
}
});
// logic to update question from array
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mQuestionNumber++;
}
}
}
I would suggest to do this:
1) Rename updateQuestion method to nextQuestion
2) Create a method to decrease the mQuestionNumber like this:
private void prevQuestion(){
if(mQuestionNumber > 0){
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mQuestionNumber--;}
}
Here's a solution accounting for bounds
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
showNextQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
showPreviousQuestion();
}
});
private void showNextQuestion() {
showQuestion(1);
}
private void showPreviousQuestion() {
showQuestion(-1);
}
private void showQuestion(int increment) {
int newQuestionNumber = mQuestionNumber + increment;
if (newQuestionNumber >= 0 && newQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionNumber = newQuestionNumber;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
}
It can be done by just adding a flag to mention the move,
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(true);
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(false);
}
});
And the method would look like:
private void updateQuestion(boolean forward) {
if(forward && mQuestionNumber < mQuestionLibrary.getLength())
mQuestionNumber++
else if (mQuestionNumber>1)
mQuestionNumber--;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
I would change the following methodes:
would remove mQuestionNummer++; from update question.
You can increment mQuestions directly in the onClickMethode of NextButton.
So you can implement your solution simply by decrement mQuestion-- in onClick of previous Button.
Code would look like this:
public class MainActivityextends AppCompatActivity {
private QuestionLibraryBeginner mQuestionLibrary = new
QuestionLibraryBeginner();
private int mQuestionNumber = 1; // current question number
//initialising navigation buttons
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
// receive the current question number from last activity by Intent
Intent intent = getIntent();
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionNumber++;
updateQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// i want it to loop backwards from here
if(mQuestionNumber > 0){
mQuestionNumber--;
updateQuestion();
}
else
{}//don't do anything to prevent IndexOutOfBounds
}
});
// logic to update question from array
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
}
}
You need to don't mess logic of your application with view logic, decouple them.
Just make class Question able to provide previous and next questions. Also according to oop principles (solid, grasp) fetch information from class and make decision outside is wrong, make class to do it's work. Oop it's about telling classes to do things, not work instead of them.
class Questions {
private int index = 0;
private String[] mQuestions;
//better to don't hardcode and provide questions in constructor
public Question(String[] questions) {
this.questions = questions;
}
//we don't need this method
int getLength(){
return mQuestions.length;
}
//provide human readable information about current position in question list
// when you want to provide this information to user introduce label field in activity
public String currentPosition() {
int questionPosition = index + 1;
int questionsLength = mQuestions.length;
return String.format("current question number is %d from %d" , questionPosition, questionsLength);
}
//return next question when available, if next not available returns last question from array
public String next() {
int lastIndex = mQuestions.length - 1;
if(index < lastIndex) {
index++;
}
return mQuestions[index];
}
//return current question
public String current() {
return mQuestions[index];
}
//return previous question when available, if previous not available returns first question from array
public String previous() {
int firstIndex = 0;
if(index > firstIndex) {
index--;
}
return mQuestions[index];
}
}
And how to use it in Activity:
public class MainActivity extends AppCompatActivity {
//better to don't hardcode here, but provide this class from
//constructor of MainActivity just like questions array provide
// to constructor in Questions class
private Questions questions = new Questions(new String[]{"q1","q2"});
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
Intent intent = getIntent();
//when create Activity populate question field with first question
mQuestionText.setText(questions.current());
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQuestionText.setText(questions.next());
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQuestionText.setText(questions.previous());
}
});
}
}
p.s. you may improve this code further in way to introduce Observer pattern, Activity is a view, Questions is model.
I am trying to make a simple quiz app and I want to display the score value in another activity(another screen) i.e. when I press the submit button the score activity should open and display the total score.
I have tried using intents but it hasn't worked. I am new at android programming and there could be some silly mistakes.
This is the MainActivity.java file.
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Question 1 Methods
public void question1_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.haibara:
if (checked) {
String correct = "Right Answer";
display_answer1(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q1_o1);
display_answer1(wrong);
}
break;
}
}
private void display_answer1(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_1);
quantityTextView.setText(answer);
}
//Question 2 Methods
public void question2_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.true_op:
if (checked) {
String correct = "Right Answer";
display_answer2(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q2_o1);
display_answer2(wrong);
}
break;
}
}
private void display_answer2(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_2);
quantityTextView.setText(answer);
}
//Question 3 Methods
public void question3_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q3_op3:
if (checked) {
String correct = "Right Answer";
display_answer3(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q3_o3);
display_answer3(wrong);
}
break;
}
}
private void display_answer3(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_3);
quantityTextView.setText(answer);
}
//Question 4 Methods
public void question4_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q4_op1:
if (checked) {
String correct = "Right Answer";
display_answer4(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q4_o1);
display_answer4(wrong);
}
break;
}
}
private void display_answer4(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_4);
quantityTextView.setText(answer);
}
//Question 5 Methods
public void question5_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q5_op3:
if (checked) {
String correct = "Right Answer";
display_answer5(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q5_o3);
display_answer5(wrong);
}
break;
}
}
private void display_answer5(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_5);
quantityTextView.setText(answer);
}
//Submit Button
public void onClickSubmit(View view){
Intent scoreActivity = new Intent(MainActivity.this,Score.class);
scoreActivity.putExtra("sendScore", score);
startActivity(scoreActivity);
}
}
This is the other activity java(Score.java) file
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class Score extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
Intent scoreActivity = getIntent();
int totalScore = scoreActivity.getIntExtra("sendScore", 0);
displayScore(totalScore);
}
public void displayScore(int score) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(score);
}
}
Try to print score on button click using log. if score is not null than write below code.
From Activity
Intent intent = new Intent(getBaseContext(), Score.class);
intent.putExtra("EXTRA_SCORE", score);
startActivity(intent);
To Activity
Intent intent = getIntent();
int intValue = intent.getIntExtra("EXTRA_SCORE", 0);
So I'm new to java and I'm trying to make quiz app as exercise. I kinda made one but it doesn't work:
public class QuizActivity extends AppCompatActivity {
TextView QuestionText;
Button button1;
Button button2;
Button button3;
Button button4;
ArrayList<Question> listOfQuestions;
int currentQuestion = 0;
Context context = this;
int NumberOfQuestions;
GameCreator game;
String totalCorrect = "";
String totalWrong = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
QuestionText = (TextView) findViewById(R.id.textJautajums);
button1 = (Button) findViewById(R.id.buttonOpcija1);
button2 = (Button) findViewById(R.id.buttonOpcija2);
button3 = (Button) findViewById(R.id.buttonOpcija3);
button4 = (Button) findViewById(R.id.buttonOpcija4);
NumberOfQuestions = Integer.parseInt(context.getString(R.string.JautajumuSkaits).toString());
game = new GameCreator(NumberOfQuestions);
listOfQuestions = game.makeQuestions();
Resources r = getResources();
int px1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 165, r.getDisplayMetrics());
button1.setWidth(px1);
button2.setWidth(px1);
button3.setWidth(px1);
button4.setWidth(px1);
Resources e = getResources();
int px2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 125, r.getDisplayMetrics());
button1.setHeight(px2);
button2.setHeight(px2);
button3.setHeight(px2);
button4.setHeight(px2);
if (currentQuestion == 0){
setQuestion(listOfQuestions.get(0));
}
button1.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button1.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button2.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button2.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button3.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button3.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button4.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button4.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
}
public void gajiens(String answer, Question thisQuestion){
if (currentQuestion < 14){
if (answer.equals(thisQuestion.getAnswer())){
totalCorrect += "Question: " + thisQuestion.getQuestion() + "\nYour Answer: " + answer + "\n";
} else {
totalWrong += "Question: " + thisQuestion.getQuestion()) + "\nYour Answer: " + answer + "\n";
}
currentQuestion++;
setQuestion(listOfQuestions.get(currentQuestion));
} else {
Intent intent = new Intent(this, EndActivity.class);
intent.putExtra("correct", totalCorrect);
intent.putExtra("wrong", totalWrong);
startActivity(intent);
}
}
public void setQuestion(Question kursh){
QuestionText.setText(kursh.getJautajums());
button1.setText(kursh.getOption1());
button2.setText(kursh.getOption2());
button3.setText(kursh.getOption3());
button4.setText(kursh.getOption4());
}
object Question is:
public Question(String Question, String Option1, String Option2, String Option3,String Option4, String correctAnswer){
Question = Question;
Option1 = Option1;
Option2 = Option2;
Option3 = Option3;
Option4 = Option4;
correctAnswer = correctAnswer;
}
Basically the problem is that App doesn't count the right answers. For some reason it most of the time uses the original text of TextView as ''correctAnswer''. Anyone has any idea what to do? I suspect since this isn't working properly this isn't particularly best approach so maybe someone can suggest a better one?
to compare the value of a TextView with a String you can do this as below
TextView tvAnswer = (TextView) findViewById(R.id.tvAnswer);
String correctAnswer = "Correct Answer";
if(correctAnswer.equals(tvAnswer.getText.toString()) )
{
//do something
}
else{
//do something
}
I am working on Timer. I have created a TextView in my Question XML(Where I have to Implement Timer to display) and PlayButton in Welcome XML (Timer in Question Activity Start When Play button Is Clicked) .I have WelcomeActivity where I have implemented PlayButton and QuestionActivity Where I wanted to Function my timer.I am attaching My Code Here:-
Welcome XML:-
<Button
android:text="Play"
android:id="#+id/playBtn"
android:layout_width="80dip"
android:layout_alignParentRight="true"
android:layout_height="wrap_content"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:textColor="#ffffff"
android:background="#drawable/start_button" />
Question XML:-
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/question"
android:layout_centerHorizontal="true"
android:background="#drawable/timer_bttn"
android:onClick="onClick"/>
Welcome Activity:-
public class WelcomeActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
//////////////////////////////////////////////////////////////////////
//////// GAME MENU /////////////////////////////////////////////////
Button playBtn = (Button) findViewById(R.id.playBtn);
playBtn.setOnClickListener(this);
Button settingsBtn = (Button) findViewById(R.id.settingsBtn);
settingsBtn.setOnClickListener(this);
Button rulesBtn = (Button) findViewById(R.id.rulesBtn);
rulesBtn.setOnClickListener(this);
Button exitBtn = (Button) findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(this);
}
/**
* Listener for game menu
*/
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.playBtn :
//once logged in, load the main page
//Log.d("LOGIN", "User has started the game");
//Get Question set //
List<Question> questions = getQuestionSetFromDb();
//Initialise Game with retrieved question set ///
GamePlay c = new GamePlay();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((CYKApplication)getApplication()).setCurrentGame(c);
//Start Game Now.. //
i = new Intent(this, QuestionActivity.class);
startActivityForResult(i, Constants.PLAYBUTTON);
break;
case R.id.rulesBtn :
i = new Intent(this, RulesActivity.class);
startActivityForResult(i, Constants.RULESBUTTON);
break;
case R.id.settingsBtn :
i = new Intent(this, SettingsActivity.class);
startActivityForResult(i, Constants.SETTINGSBUTTON);
break;
case R.id.exitBtn :
finish();
break;
}
}
QuestionActivity:-
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
protected TextView txtTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
/**
* Configure current game and get question
*/
currentGame = ((CYKApplication)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button nextBtn1 = (Button) findViewById(R.id.answer1);
nextBtn1.setOnClickListener(this);
Button nextBtn2 = (Button) findViewById(R.id.answer2);
nextBtn2.setOnClickListener(this);
Button nextBtn3 = (Button) findViewById(R.id.answer3);
nextBtn3.setOnClickListener(this);
Button nextBtn4 = (Button) findViewById(R.id.answer4);
nextBtn4.setOnClickListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current games
* current question
*/
private void setQuestions() {
//set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion());
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
//set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
#Override
public void onClick(View arg0) {
//Log.d("Questions", "Moving to next question");
setTimer();
/**
* check if end of game
*/
if (currentGame.isGameOver()){
//Log.d("Questions", "End of game! lets add up the scores..");
//Log.d("Questions", "Questions Correct: " + currentGame.getRight());
//Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
}
else{
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it
* has then check if its correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer==null){
//Log.d("Questions", "No Checkbox selection made - returning");
return false;
}
else {
//Log.d("Questions", "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
//Log.d("Questions", "Correct Answer!");
currentGame.incrementScore();
}
else{
//Log.d("Questions", "Incorrect Answer!");
currentGame.decrementScore();
}
return true;
}
}
/**
*
*/
private String getSelectedAnswer() {
Button c1 = (Button)findViewById(R.id.answer1);
Button c2 = (Button)findViewById(R.id.answer2);
Button c3 = (Button)findViewById(R.id.answer3);
Button c4 = (Button)findViewById(R.id.answer4);
if (c1.callOnClick())
{
return c1.getContext().toString();
}
if (c2.callOnClick())
{
return c2.getContext().toString();
}
if (c3.callOnClick())
{
return c3.getContext().toString();
}
if (c4.callOnClick())
{
return c4.getContext().toString();
}
return null;
}
public void setTimer() {
long finishTime = 5;
CountDownTimer counterTimer = new CountDownTimer(finishTime * 1000, 1000) {
public void onFinish() {
//code to execute when time finished
}
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
txtTimer.setText("" + minutes + ":0" + seconds);
} else {
txtTimer.setText("" + minutes + ":" + seconds);
}
}
};
counterTimer.start();
}
}
I am trying To add A function in QuestionActivity But I don't know how to proceed to call my timer One activity to another Activity. so that my timer display on Question XMl after Clicking the Play Button In Welcome XMl.Can anyone help me How to add listener in another activity Or some other way to solve My Problem.
thank's in Advance
why would you start the timer when the button is clicked?
you can set the button to go to the next activity and start the timer on that activity when
it is called...
(sorry this is what i understand with your question: you want the timer to start when the button is clicked and the timer is on another activity?)