I've build an quiz app so I can practice myself with different question. I want to make sure that once I provides an answer for a particular question, the question get disable to prevent multiple answers being entered, as well I know it's in the Toast section but i'm looking to add a final score at the end in percentage. I would greatly appreciate some help.
package com.example.randomuser.androidquiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPreviousButton;
private TextView mQuestionTextView;
private int mCurrentIndex = 0;
private static final String KEY_INDEX = "index";
private Question[] mQuestionBank = new Question[] {
new Question(R.string.quiz_questionone, false),
new Question(R.string.quiz_questiontwo, true),
new Question(R.string.quiz_questionthree, true),
new Question(R.string.quiz_questionfour, false),
new Question(R.string.quiz_questionfive, true),
new Question(R.string.quiz_questionsix, false),
new Question(R.string.quiz_questionseven, true),
new Question(R.string.quiz_questioneight, false),
new Question(R.string.quiz_questionnine, false),
new Question(R.string.quiz_questionten, true),
new Question(R.string.quiz_questionelevn, false),
new Question(R.string.quiz_questiontwelve, false),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
if(savedInstanceState != null)
{
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
mQuestionTextView = (TextView) findViewById(R.id.question_textview);
updateQuestion();
mQuestionTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex + 1)% mQuestionBank.length;
updateQuestion();
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View view ) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
mPreviousButton = (ImageButton) findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View view ) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
if(mCurrentIndex < 0){
mCurrentIndex = 0;
}
updateQuestion();
}
});
mFalseButton = (Button) findViewById(R.id.falseButton);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
mTrueButton = (Button) findViewById(R.id.trueButton);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
}
});
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userGuess)
{
boolean a = mQuestionBank[mCurrentIndex].isAnswer();
int messageId = 0;
if(userGuess == a)
{
messageId = R.string.right_answer;
}
else{
messageId = R.string.wrong_answer;
}
Toast toast= Toast.makeText(QuizActivity.this, messageId, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 0, 300);
toast.show();
}
#Override
protected void onSaveInstanceState( Bundle outState ) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_INDEX, mCurrentIndex);
}
}
Related
first of all pardon my English, but I think it's understandable.
So in this app is a counter and I need it to do sound when it reaches for example 30 seconds.
note: this is my first question here so if I broke any rules or I could have asked better way, let me know please
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
public class MainActivity extends AppCompatActivity {
private Button mStartButton;
private Button mPauseButton;
private Button mResetButton;
private Chronometer mChronometer;
private long lastPause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStartButton = (Button) findViewById(R.id.start_button);
mPauseButton = (Button) findViewById(R.id.pause_button);
mResetButton = (Button) findViewById(R.id.reset_button);
mChronometer = (Chronometer) findViewById(R.id.chronometer);
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (lastPause != 0){
mChronometer.setBase(mChronometer.getBase() + SystemClock.elapsedRealtime() - lastPause);
}
else{
mChronometer.setBase(SystemClock.elapsedRealtime());
}
mChronometer.start();
mStartButton.setEnabled(false);
mPauseButton.setEnabled(true);
}
});
mPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
mChronometer.stop();
mPauseButton.setEnabled(false);
mStartButton.setEnabled(true);
}
});
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mChronometer.stop();
mChronometer.setBase(SystemClock.elapsedRealtime());
lastPause = 0;
mStartButton.setEnabled(true);
mPauseButton.setEnabled(false);
}
});
}
}
Define global integer variable as counter and count it in Chronometer's OnChronometerTickListener, and when it reach for example 30 then play sound and reset your counter:
int c = -1; // define global
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
c++;
if(c == 30) {
c = 0;
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.ding);
mp.start();
}
}
});
I've already made a button that when pressed goes into an array of notes and chooses one randomly, what I don't know how to do is have a button that replays that random note whenever pressed. I was thinking of using the rSound integer but since it's in a private void I can't use it.. How should i go about this?
Code:
package com.stefanawesome.piano;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
//Declaring variables and array:
ImageButton NoteNew;
ImageButton Repeat;
Button c, d, e, f, g, a, b, high;
List<Integer> soundList = new ArrayList<Integer>();
private SoundPool soundpool;
private int sound_c, sound_d, sound_e, sound_f, sound_g, sound_a, sound_b, sound_high;
//Random Note Function:
private void playRandomSound() {
int randomInt = (new Random().nextInt(soundList.size()));
int rSound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(this, rSound);
mp.start();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Find View by ID all here:
soundList.add(R.raw.c);
soundList.add(R.raw.d);
soundList.add(R.raw.e);
soundList.add(R.raw.f);
soundList.add(R.raw.g);
soundList.add(R.raw.a);
soundList.add(R.raw.b);
soundList.add(R.raw.chigh);
NoteNew = (ImageButton) findViewById(R.id.Newnote);
Repeat = (ImageButton) findViewById(R.id.Repeat);
c = (Button) findViewById(R.id.C);
d = (Button) findViewById(R.id.D);
e = (Button) findViewById(R.id.E);
f = (Button) findViewById(R.id.F);
g = (Button) findViewById(R.id.G);
a = (Button) findViewById(R.id.A);
b = (Button) findViewById(R.id.B);
high = (Button) findViewById(R.id.high);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
soundpool = new SoundPool.Builder().setMaxStreams(5).build();
} else {
soundpool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
}
//Soundpools over here:
sound_c = soundpool.load(this, R.raw.c, 1);
sound_d = soundpool.load(this, R.raw.d, 1);
sound_e = soundpool.load(this, R.raw.e, 1);
sound_f = soundpool.load(this, R.raw.f, 1);
sound_g = soundpool.load(this, R.raw.g, 1);
sound_a = soundpool.load(this, R.raw.a, 1);
sound_b = soundpool.load(this, R.raw.b, 1);
sound_high = soundpool.load(this, R.raw.chigh, 1);
//When button gets clicked do something:
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_c, 1, 1, 0, 0, 1);
}
});
d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_d, 1, 1, 0, 0, 1);
}
});
e.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_e, 1, 1, 0, 0, 1);
}
});
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_f, 1, 1, 0, 0, 1);
}
});
g.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_g, 1, 1, 0, 0, 1);
}
});
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_a, 1, 1, 0, 0, 1);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_b, 1, 1, 0, 0, 1);
}
});
high.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_high, 1, 1, 0, 0, 1);
}
});
NoteNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playRandomSound();
}
});
}
}
Just save the random integer(which s the index of the random note) in some other variable.
Then, use that variable to replay the last random note.
Update your function to
int last;
private void playRandomSound() {
int randomInt = (new Random().nextInt(soundList.size()));
last=randomInt;
int rSound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(this, rSound);
mp.start();
}
And add this new function(call it with new button)
private void playlastRandomSound() {
int rSound = soundList.get(last);
MediaPlayer mp = MediaPlayer.create(this, rSound);
mp.start();
}
package com.example.tobiadegoroye.pokemonsoundboard;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class PokemonSoundboard extends AppCompatActivity {
MediaPlayer psyduckplayer; //member variable
MediaPlayer pikachuplayer; //member variable
MediaPlayer diglettplayer; //member variable
ImageButton mpsyduckbutton;
ImageButton mpikachubutton;
ImageButton mdiglettbutton;
View.OnClickListener psyducklistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
psyduckplayer.start();
}
};
View.OnClickListener pikachulistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
pikachuplayer.start();
}
};
View.OnClickListener digletlistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
diglettplayer.start();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon_soundboard);
mpsyduckbutton = (ImageButton) findViewById(R.id.psyduckbutton);
mpikachubutton = (ImageButton) findViewById(R.id.pikachubutton);
mdiglettbutton = (ImageButton) findViewById(R.id.diglettbutton);
psyduckplayer = MediaPlayer.create(this,R.raw.psyduck);
pikachuplayer = MediaPlayer.create(this,R.raw.pikachu);
diglettplayer = MediaPlayer.create(this,R.raw.diglett);
mpsyduckbutton.setOnClickListener(psyducklistner);
mpikachubutton.setOnClickListener(pikachulistner);
mdiglettbutton.setOnClickListener(digletlistner);
}
}
Use the MediaPlayer.isPlaying() and MediaPlayer.stop() methods.
public void stopPlaying()
{
if(pikachuplayer != null && pikachuplayer.isPlaying())
{
pikachuplayer.stop();
}
if(digletplayer != null && digletplayer.isPlaying())
{
digletplayer.stop();
}
if(psyduckplayer != null && psyduckplayer.isPlaying())
{
psyduckplayer.stop();
}
}
View.OnClickListener psyducklistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
psyduckplayer.start();
}
};
View.OnClickListener pikachulistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
pikachuplayer.start();
}
};
View.OnClickListener digletlistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
diglettplayer.start();
}
};
View.OnClickListener digletlistner = new View.OnClickListener() {
#Override
public void onClick(View v) {
diglettplayer.start();
}
};
The stopPlaying() method stops all Medias from playing, only if they're playing and not null (They probably aren't null, as they're member variables, but it's still a good practice).
So I just started programming, but I dont really get the method OnClickListener. I already google the error I have: "The type new View.OnClickListener(){} must implement the inherited abstract method View.OnClickListener.OnClick(View)" and I tried to change some things in my code, but it still doens't work. Can anyone tell me exactly what I need to change in my code? Thanks in advance.
MainMenuScreen.java:
package com.wouter.testjk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainMenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_menu);
//error on the line below
((Button) findViewById(R.id.one_player)).setOnClickListener(new OnClickListener() { //the error is here
public void onClick(View V) {
Log.d("DEBUG", "One Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", true);
startActivityForResult(intent, 0);
}
});
((Button) findViewById(R.id.two_player)).setOnClickListener(new OnClickListener() {
public void onClick(View V) {
Log.d("DEBUG", "Two Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", false);
startActivityForResult(intent, 0);
}
});
((Button) findViewById(R.id.exit_game)).setOnClickListener(new OnClickListener() {
public void onClick(View V) {
Log.d("DEBUG", "Exit Game Button Pressed!");
MainMenuScreen.this.finish();
}
});
}
}
MainActivity.java:
package com.wouter.testjk;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.wouter.testjk.R;
public class MainActivity extends Activity implements OnClickListener{
private TicTacToeGame mGame;
private Button mBoardButtons[];
private TextView mInfoTextView;
private TextView mPlayeroneCount;
private TextView mTieCount;
private TextView mPlayertwoCount;
private TextView mPlayeroneText;
private TextView mPlayertwoText;
private int mPlayeroneCounter = 0;
private int mTieCounter = 0;
private int mPlayertwoCounter = 0;
private boolean mPlayeroneFirst = true;
private boolean mIsSinglePlayer = false;
private boolean mIsPlayerOneTurn = true;
private boolean mGameOver = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
boolean mGameType = getIntent().getExtras().getBoolean("gametype");
mBoardButtons = new Button[mGame.getBOARD_SIZE()];
mBoardButtons[0] = (Button) findViewById(R.id.one);
mBoardButtons[1] = (Button) findViewById(R.id.two);
mBoardButtons[2] = (Button) findViewById(R.id.three);
mBoardButtons[3] = (Button) findViewById(R.id.four);
mBoardButtons[4] = (Button) findViewById(R.id.five);
mBoardButtons[5] = (Button) findViewById(R.id.six);
mBoardButtons[6] = (Button) findViewById(R.id.seven);
mBoardButtons[7] = (Button) findViewById(R.id.eight);
mBoardButtons[8] = (Button) findViewById(R.id.nine);
Button mTen = (Button) findViewById(R.id.ten);
mTen.setOnClickListener(this);
Button mEleven = (Button) findViewById(R.id.eleven);
mEleven.setOnClickListener(this);
mInfoTextView = (TextView) findViewById(R.id.information);
mPlayeroneCount = (TextView) findViewById(R.id.humancount);
mTieCount = (TextView) findViewById(R.id.tiesCount);
mPlayertwoCount = (TextView) findViewById(R.id.androidCount);
mPlayeroneText = (TextView) findViewById(R.id.human);
mPlayertwoText = (TextView) findViewById(R.id.android);
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mTieCount.setText(Integer.toString(mTieCounter));
mPlayeroneCount.setText(Integer.toString(mPlayertwoCounter));
mGame = new TicTacToeGame();
startNewGame(mGameType);
}
private void startNewGame(boolean isSingle)
{
//some code here
}
private class ButtonClickListener implements View.OnClickListener
{
int location;
public ButtonClickListener(int location)
{
this.location = location;
}
#Override
public void onClick(View view) {
if (!mGameOver)
{
if(mBoardButtons[location].isEnabled())
{
if(mIsSinglePlayer)
{
setMove(mGame.PLAYER_ONE, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
winner = mGame.checkForWinner();
}
if (winner == 0)
mInfoTextView.setText(R.string.turn_human);
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner ==2)
{
mInfoTextView.setText(R.string.result_human_wins);
mPlayeroneCounter++;
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mGameOver = true;
}
else if (winner ==3)
{
mInfoTextView.setText(R.string.result_android_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
else
{
if(mIsPlayerOneTurn)
{
setMove(mGame.PLAYER_ONE, location);
}
else
{setMove(mGame.PLAYER_TWO, location);
}
int winner = mGame.checkForWinner();
if (winner == 0)
{
if(mIsPlayerOneTurn)
{
mInfoTextView.setText(R.string.turn_player_two);
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_one);
mIsPlayerOneTurn = true;
}
}
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner ==2)
{
mInfoTextView.setText(R.string.player_one_wins);
mPlayeroneCounter++;
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mGameOver = true;
}
else if (winner ==3)
{
mInfoTextView.setText(R.string.player_two_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
}
}
}
}
private void setMove(char player, int location)
{
mGame.setMove(player,location);
mBoardButtons[location].setEnabled(false);
mBoardButtons[location].setText(String.valueOf(player));
if (player == mGame.PLAYER_ONE)
mBoardButtons[location].setTextColor(Color.GREEN);
else
{
mBoardButtons[location].setTextColor(Color.RED);
}
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.ten:
startNewGame(mIsSinglePlayer);
return;
case R.id.eleven:
MainActivity.this.finish();
return;
}
}
}
Sounds like a project error. First follow good code guidelines.
When overriding a method (e.g. onClick) add an #Override annotation before it. This will make the compiler yell, if such method doesn't exist.
Specify which class your interface belongs to by using View.OnClickListener.
Button already is a View, no need to cast it just to set a OnClickListener.
Here's what it might look like:
// No need to cast it to a button here, as it
findViewById(R.id.one_player).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("DEBUG", "One Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", true);
startActivityForResult(intent, 0);
}
});
Lastly clean/rebuild your project as this error doesn't occur to me when using your code.
OnClickListener is an interface that defines the method void onClick(View v). Adding the implements OnClickListener to you Activity class means that that class implements the interface and thus must have that onClick(View view) method. This is mainly done so that you can pass this on places an OnClickListener is needed and which you also did.
But, as you coded it, you should remove the implements OnClickListenerpart from your Activity and instead pass instances of your ButtonClickListener class as OnClickListeners to your buttons like so:
Button mTen = (Button) findViewById(R.id.ten);
mTen.setOnClickListener(new ButtonClickListener(10)); /* 10 is just a guess */
Button mEleven = (Button) findViewById(R.id.eleven);
mEleven.setOnClickListener(new ButtonClickListener(11)); /* 11 is just a guess */
I Have an app in which the main activity shows a question and has true button false button and cheat button
When user press the correct option, listener will Toast Correct.. and otherwise listener will Toast Incorrect
Now when we press the cheat button new activity is launched and has a textview "Are you sure you want to cheat?", another textview which is blank and a show answer button..
When user presses the show answer button , the blank text view is set to the answer of the question (as asked in the main activity)
And when the user goes back the true and false button onClickListeners are now set to make a toast "Cheating is wrong"
i have declared a boolean value which is set to false, the boolean value is set to True and i save it in the bundle so that when the user rotates the screen , the value of the variable is not overwritten on onCreate(..) method being recalled..
I tried debugging with break points in eclipse , the value is not overridden still on main activity "Cheating is wrong" doesnt show up , it shows Correct or Incorrect..
QuizActivity : Launcher Activity
CheatActivity: Activity launched on onCreate
TrueFalse activity : creating array of objects with fields (question and answer)
Following is the code : QuizActivity.java (Launcher activity)
package com.mhrsolanki2020.geoquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton, mFalseButton, mNextButton, mCheatButton;
private TextView mQuestionTextView;
private static final String KEY_INDEX = "index";
private static final String TAG = "QuizActivity";
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true) };
private int mCurrentIndex = 0;
private boolean mIsCheater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
mIsCheater=false;
}
});
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answer = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answer);
startActivityForResult(i, 0);
}
});
if (savedInstanceState != null)
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater) {
messageResId = R.string.judgement_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
} else {
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN,
false);
Log.d(TAG, "Value of mIsCheater : " + mIsCheater);
}
}
}
The following is the code : CheatActivity.java
package com.mhrsolanki2020.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.mhrsolanki2020.geoquiz.anwer_is_true ";
public static final String EXTRA_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_shown";
public static final String EXTRA_IS_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_is_shown";
boolean mCorrectAnswer;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mIsAnswerShown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mCorrectAnswer = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE,
false);
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
if (savedInstanceState != null) {
mIsAnswerShown = savedInstanceState.getBoolean(
EXTRA_IS_ANSWER_SHOWN, false);
} else {
mIsAnswerShown = false;
}
mShowAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mCorrectAnswer) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
}
});
}
public void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
mIsAnswerShown = isAnswerShown;
data.putExtra(EXTRA_ANSWER_SHOWN, mIsAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(EXTRA_IS_ANSWER_SHOWN, mIsAnswerShown);
}
}
Following is the code : TrueFalse.java
package com.mhrsolanki2020.geoquiz;
public class TrueFalse {
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}
http://developer.android.com/guide/topics/resources/runtime-changes.html check this link
For orientation support do this in manifest.xml
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
In Class file, override the onSaveInstanceState(Bundle outState).