preventing a user from entering multiple answer - java

i create a true/false quiz app. in that app i have 4 buttons i.e True,False,previous(to get back to previous question),next(to get the next question). i want to add a functionality when a user click on true or false button its get disable for that question so the user can click only once for one question.
i tried to disable the button by using button.setEnabled(false) but when i click on previous button or next button the true/false buttons enabled.i want that the user can click the answer only once it does not matter how much the user traverse the question.
i try to call the setEnabledButton() in previous on click button but it disable the button but it also disable whether the user click on answer or not.
Button btrue,bfalse,bnext,bprevious;
TextView tquestion;
int mCurrentIndex=0;
Questions[] questionbank;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btrue=findViewById(R.id.true_button);
bfalse=findViewById(R.id.false_button);
bnext=findViewById(R.id.next_button);
tquestion=findViewById(R.id.question_text);
bprevious=findViewById(R.id.previous_button);
questionbank = new Questions[]
{
new Questions(R.string.greater,false),
new Questions(R.string.Pm,true),
new Questions(R.string.capital,true),
new Questions(R.string.china,false),
new Questions(R.string.Richer,false),
new Questions(R.string.company,true),
new Questions(R.string.company1,false),
};
update();
bnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int s=questionbank.length;
if( mCurrentIndex<=s )
{
if (mCurrentIndex + 1 < questionbank.length) {
mCurrentIndex++;
}
else
{ Toast.makeText(getApplicationContext(),"not more question",Toast.LENGTH_SHORT).show();
}
update();
}
}
});
btrue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(true);
}
});
bfalse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
bprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentIndex > 0) {
mCurrentIndex = (mCurrentIndex - 1);
update();
}
else
{ Toast.makeText(getApplicationContext(), "cant go back", Toast.LENGTH_SHORT).show(); }
}
});
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
setButtonEnabled(true);
}
private void checkAnswer(boolean userPressedTrue)
{
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
private void setButtonEnabled(boolean enabled) {
btrue.setEnabled(enabled);
bfalse.setEnabled(enabled);
}
}

In Questions class you can create a method,
public class Questions {
boolean isQuestionAnswered;
public boolean isQuestionAnswered() {
return isQuestionAnswered;
}
public void setQuestionAnswered(boolean questionAnswered) {
isQuestionAnswered = questionAnswered;
}
}
private void checkAnswer(boolean userPressedTrue)
{
questionbank[mCurrentIndex].setQuestionAnswered(true);
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
if(questionbank[mCurrentIndex].isQuestionAnswered())
setButtonEnabled(false);
else
setButtonEnabled(true);
}
Try this out and check whether this solves your problem

Related

when i press dot button i want that dot button press only one time in input 1?

package com.deitel.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double input1 = 0, input2 = 0d ,count=0;
Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn_dot, btn_equal, btn_subtract, btn_multi, btn_add, btn_devision, btn_clear, btn_back;
TextView text_result;
boolean Addition, Subtraction, Multiplication, Devision, decimal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btn_dot = findViewById(R.id.btn_dot);
btn_equal = findViewById(R.id.btn_equal);
btn_add = findViewById(R.id.btn_add);
btn_subtract = findViewById(R.id.btn_subtract);
btn_multi = findViewById(R.id.btn_multi);
btn_devision = findViewById(R.id.btn_devision);
btn_clear = findViewById(R.id.btn_clear);
btn_back = findViewById(R.id.btn_back);
text_result = findViewById(R.id.text_result);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "9");
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Addition = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Subtraction = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_multi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Multiplication = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_devision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Devision = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText("");
input1 = 0.0;
input1 = 0.0;
}
});
btn_dot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
count=1;
text_result.setText(text_result.getText()+".");
return;
}
else{
text_result.setText(text_result.getText()+"0.");
decimal=true;
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = text_result.getText().toString();
int input = number.length();
if (input > 0) {
text_result.setText(number.substring(0, input - 1));
}
}
});
btn_equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count=0;
if ((Addition || Subtraction || Multiplication || Devision) ) {
if (text_result.getText().toString().trim().equals("")){
input2=0;
return;
}else {
input2 = Float.parseFloat(text_result.getText() + "");
}
}
if (Addition) {
text_result.setText(input1 + input2 + "");
Addition = false;
}
if (Subtraction) {
text_result.setText(input1 - input2 + "");
Subtraction = false;
}
if (Multiplication) {
text_result.setText(input1 * input2 + "");
Multiplication = false;
}
if (Devision) {
text_result.setText(input1 / input2 + "");
Devision = false;
}
}
});
}
}
When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
But this code doesn't meet that requirements - it displays 2.3.4.5 etc..but I want only one dot in one input. When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
Here you can manage that with simple flag.
public class MainActivity extends AppCompatActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide};
// TextView used to display the output
private TextView txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
/**
* Find and set OnClickListener to numeric buttons.
*/
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
/**
* Find and set OnClickListener to operator buttons, equal button and decimal point button.
*/
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
}
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
/**
* Logic to calculate the solution.
*/
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
if (lastNumeric && !stateError) {
// Read the expression
String txt = txtScreen.getText().toString();
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}

CountDownTimer is not stopping on BackPressed running in background,may be handler.postDelayed() is the issue. How to fix it in this code?

My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}

i want to reset the seekbar to start position once the music is played and button showing "play"

i want to reset the seekbar to start position once the music is played and button showing "play"...The problem with the code is that the seek bar stays at the end position after its done playing the music and button still shows "pause"...
Here's my code
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable, View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play", Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
MediaPlayer has got onCompletionListener(), you can use that. Your code with handlers is not too reliable, it would be better to refactor it.
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do whatever you want
}
});

app is crashing because of an Activity invokation

I'm trying to invoke an activity from the MainActivity via a button with OnClickListener
The first activity is responding and works, the second activity doesn't work and crashes the application
Please help me to find the solution
Thanks!!!
here is the code:
class Layout{
public Layout(){
btnStopWatch = (Button)findViewById(R.id.btnStopWatch);
btnTimer = (Button)findViewById(R.id.btnTimer);
}
Button btnStopWatch, btnTimer;
}
class Event{
public Event(){
l.btnStopWatch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), StopWatchActivity.class);
startActivity(i);
}
});
l.btnTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), TimerActivity.class);
startActivity(i);
}
});
}
}
Layout l; Event e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = new Layout(); e = new Event();
}}
First Activity that works:
public class StopWatchActivity extends AppCompatActivity {
class Layout{
public Layout(){
tvHours = (TextView)findViewById(R.id.tvHours);
tvMinutes = (TextView)findViewById(R.id.tvMinutes);
tvSeconds = (TextView)findViewById(R.id.tvSeconds);
tvBack = (TextView)findViewById(R.id.tvBack);
btnStartStop = (Button)findViewById(R.id.btnStartStop);
btnReset = (Button)findViewById(R.id.btnReset);
}
TextView tvHours, tvMinutes, tvSeconds, tvBack;
Button btnStartStop, btnReset;
}
class Event{
public Event(){
l.btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isStarted){
Stop();
}else {
Start();
}
}
});
l.btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Reset();
}
});
l.tvBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
Layout l; Event e;
boolean isStarted = false;
int sec = 0, min = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_watch);
l = new Layout(); e = new Event();
}
public void Start(){
l.btnStartStop.setText("Stop");
isStarted = true;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (isStarted){
try{
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(isStarted){
MoveTime();
}
}
});
}catch (InterruptedException e){
}
}
}
});
t.start();
}
public void MoveTime(){
sec++;
if (sec >= 59){
sec = 0;
min++;
if(min >= 59){
min = 0;
hour++;
}
}
UpdateScreen();
}
public void UpdateScreen(){
l.tvHours.setText(Format(hour));
l.tvMinutes.setText(Format(min));
l.tvSeconds.setText(Format(sec));
}
public void CleanScreen(){
l.tvHours.setText("00");
l.tvMinutes.setText("00");
l.tvSeconds.setText("00");
}
public String Format(int i){
if (i<=9){
return "0" + i;
}else{
return Integer.toString(i);
}
}
public void Stop(){
isStarted = false;
l.btnStartStop.setText("Start");
}
public void Reset(){
if(isStarted)
Stop();
CleanScreen();
sec = 0;
min = 0;
hour = 0;
}}
second activity that doesn't work:
public class TimerActivity extends AppCompatActivity {
class Layout {
public Layout() {
etHour = (EditText) findViewById(R.id.etHour);
etHour.setFilters(new InputFilter[]{new InputFilterMinMax("0", "24")});
etMin = (EditText) findViewById(R.id.etMin);
etMin.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
etSec = (EditText) findViewById(R.id.etSec);
etSec.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
btnStartStop = (Button) findViewById(R.id.btnStartStop);
btnReset = (Button) findViewById(R.id.btnReset);
tvBack1 = (TextView)findViewById(R.id.tvBack);
}
EditText etHour, etMin, etSec;
Button btnStartStop, btnReset;
TextView tvBack1;
}
class Event {
public Event() {
l.btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted) {
Stop();
} else {
Start();
}
}
});
l.btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Reset();
}
});
l.tvBack1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
}
Layout l;
Event e;
boolean isStarted = false;
int sec = 0, min = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
l = new Layout();
e = new Event();
}
public void Start() {
l.btnStartStop.setText("Stop");
isStarted = true;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (isStarted) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (isStarted) {
MoveTime();
}
}
});
} catch (InterruptedException e) {
}
}
}
});
t.start();
}
public void MoveTime() {
sec = Integer.valueOf(l.etSec.getText().toString());
min = Integer.valueOf(l.etMin.getText().toString());
hour = Integer.valueOf(l.etHour.getText().toString());
sec--;
if (sec < 0) {
sec = 59;
min--;
if (min < 0) {
min = 59;
hour--;
}
}
UpdateScreen();
if (hour == 0) {
if (min == 0) {
if (sec == 0) {
Stop();
}
}
}
}
public void UpdateScreen(){
l.etHour.setText(Format(hour));
l.etMin.setText(Format(min));
l.etSec.setText(Format(sec));
}
public void CleanScreen(){
l.etHour.setText("00");
l.etMin.setText("00");
l.etSec.setText("00");
}
public String Format(int i){
if (i<=9){
return "0" + i;
}else{
return Integer.toString(i);
}
}
public void Stop(){
isStarted = false;
l.btnStartStop.setText("Start");
}
public void Reset(){
if(isStarted)
Stop();
CleanScreen();
sec = 0;
min = 0;
hour = 0;
}}

Array is getting Wiped

So I am in the middle of a Challenge from a book I am reading. The challenge says that I do some questions at the users of the app and they should answer True or False. Also they have the option to cheat but when they gone back to the question answer must not be acceptable.
So I created a Boolean Array where I save the status of the "cheater". True if he cheats and False if he doesn't cheat. But after one full rotation of the Questions the Array is Wiped. Why is this happening? What I am doing wrong?
Here is my main code for the Quiz Activity:
public class QuizActivity extends Activity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final String CHEATER_BOOLEAN = "cheat";
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 boolean[] mCheatBank = new boolean[mQuestionBank.length];
private int mCurrentIndex = 0;
private boolean mIsCheater;
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.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mQuestionTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = mCheatBank[mCurrentIndex];
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this,CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i,0);
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater = savedInstanceState.getBoolean(CHEATER_BOOLEAN, false);
}
updateQuestion();
} // End of onCreate(Bundle) method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult called");
if (data == null) {
return;
}
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
mCheatBank[mCurrentIndex] = mIsCheater;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(CHEATER_BOOLEAN, mIsCheater);
}
Edit 1: Here is the code from the other classes because someone asked.
CheatActivity Code:
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerrandch.android.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown";
private boolean mAnswerIsTrue;
private boolean mCheater;
private TextView mAnswerTextView;
private Button mShowAnswer;
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
mCheater = false;
if (savedInstanceState != null) {
mCheater = savedInstanceState.getBoolean(EXTRA_ANSWER_SHOWN, false);
setAnswerShownResult(mCheater);
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
} else {
setAnswerShownResult(false);
}
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
mCheater = true;
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(EXTRA_ANSWER_SHOWN, mCheater);
}
}
TrueFalse Code:
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;
}
}
It's not entirely clear what you mean by wiped. But I think your problem is that you are using a member variable to set your array values. So you are setting each element of your array to that value. So essentially the entire array will be set to what ever the final state of mIsCheater is.

Categories

Resources