What am i doing wrong at my simple android app? - java

I am trying to make a app that has a switch a button and a text and if you turn the switch on and press the button; the number displayed on the text will be added by 1. But if the switch is turned off the number will be subtracted by 1.
but when i run my app and press the button, the app crashes...
i do not have much experience at programming and i do not know what im doing wrong. and i have only tried this code.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView)findViewById(R.id.textView);
final Button button = (Button)findViewById(R.id.button);
Switch mySwitch = (Switch)findViewById(R.id.mySwitch);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked== true){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(text_int);
}
});
}
if (isChecked == false) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(text_int);
}
});
}
}
});
}
}
so this should behave as i described earlier but it doesn't.

Your app crashes because you are trying to set an int to a textview.setText()and when you pass an int to this method it expects it to be a resource id and which could not be found in your case that's why it will throw ResourceNotFoundException and crashes.
You should set text as following:
text.setText(String.valueOf(text_int));

You’re nesting listeners but that logic doesn’t work sequentially. You should declare your listeners separately. I suggest you create a boolean that holds the state of the switch and one button listener. Within the listener check if switch is enabled then run your calculations and do the same if the switch is disabled.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mySwitch.isChecked(){
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(String.valueOf(text_int));
} else {
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(String.valueOf(text_int));
}
}
});

You don't need a listener for the Switch, but only 1 listener for the Button:
final TextView text = (TextView)findViewById(R.id.textView);
final Button button = (Button)findViewById(R.id.button);
final Switch mySwitch = (Switch)findViewById(R.id.mySwitch);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text_string = text.getText().toString();
int text_int = 0;
try {
text_int = Integer.parseInt(text_string);
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (mySwitch.isChecked())
text_int++;
else
text_int--;
text.setText("" + text_int);
}
});
Every time you click the Button, in its listener the value in the TextView is increased or decreased depending on whether the Switch is checked or not.

Related

Quiz app not showing dialog in last question

So when the last question is asked on the quiz, it doesn't show the dialog box if it is correct or not. And by the results screen the last question is always considered as 'correct'
public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
Button pause;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
MediaPlayer mysong;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
mysong = MediaPlayer.create(MainGameActivity.this,R.raw.hs);
mysong.start();
int media_length;
//Initializing variables
questionText = (TextView) findViewById(R.id.triviaQuestion);
pause = (Button) findViewById(R.id.pause);
buttonA = (FButton) findViewById(R.id.buttonA);
buttonB = (FButton) findViewById(R.id.buttonB);
buttonC = (FButton) findViewById(R.id.buttonC);
buttonD = (FButton) findViewById(R.id.buttonD);
triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
timeText = (TextView) findViewById(R.id.timeText);
resultText = (TextView) findViewById(R.id.resultText);
coinText = (TextView) findViewById(R.id.coinText);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pausedialog();
}
});
//Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
triviaQuizText.setTypeface(sb);
questionText.setTypeface(tb);
buttonA.setTypeface(tb);
buttonB.setTypeface(tb);
buttonC.setTypeface(tb);
buttonD.setTypeface(tb);
timeText.setTypeface(tb);
resultText.setTypeface(sb);
coinText.setTypeface(tb);
//Our database helper class
triviaQuizHelper = new TriviaQuizHelper(this);
//Make db writable
triviaQuizHelper.getWritableDatabase();
//It will check if the ques,options are already added in table or not
//If they are not added then the getAllOfTheQuestions() will return a list of size zero
if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
//If not added then add the ques,options in table
triviaQuizHelper.allQuestion();
}
//This will return us a list of data type TriviaQuestion
list = triviaQuizHelper.getAllOfTheQuestions();
//Now we gonna shuffle the elements of the list so that we will get questions randomly
Collections.shuffle(list);
//currentQuestion will hold the que, 4 option and ans for particular id
currentQuestion = list.get(qid);
//countDownTimer
countDownTimer = new CountDownTimer(22000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to timeText
timeText.setText(String.valueOf(timeValue) + "\"");
//With each iteration decrement the time by 1 sec
timeValue -= 1;
//This means the user is out of time so onFinished will called after this iteration
if (timeValue == -1) {
//Since user is out of time setText as time up
// resultText.setText(getString(R.string.timeup));
timeUp();
//Since user is out of time he won't be able to click any buttons
//therefore we will disable all four options buttons using this method
// disableButton();
}
}
//Now user is out of time
public void onFinish() {
//We will navigate him to the time up activity using below method
//timeUp();
}
}.start();
//This method will set the que and four options
updateQueAndOptions();
}
public void updateQueAndOptions() {
//This method will setText for que and options
questionText.setText(currentQuestion.getQuestion());
buttonA.setText(currentQuestion.getOptA());
buttonB.setText(currentQuestion.getOptB());
buttonC.setText(currentQuestion.getOptC());
buttonD.setText(currentQuestion.getOptD());
timeValue = 20;
//Now since the user has ans correct just reset timer back for another que- by cancel and start
countDownTimer.cancel();
countDownTimer.start();
//set the value of coin text
coinText.setText(String.valueOf(coinValue));
//Now since user has ans correct increment the coinvalue
coinValue++;
}
public void buttonA(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonB(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonC(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonD(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonPressed(Button button) {
if (qid < list.size() - 1) {
disableButton();
if (button.getText().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
incorrectDialog();
coinValue--;
}
} else {
gameWon();
}
}
//This method will navigate from current activity to GameWon
public void gameWon() {
Intent intent = new Intent(this, GameWon.class);
intent.putExtra("score", coinValue);
startActivity(intent);
finish();
}
//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
Intent intent = new Intent(this, PlayAgain.class);
startActivity(intent);
finish();
}
//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
Intent intent = new Intent(this, Time_Up.class);
startActivity(intent);
finish();
}
//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
#Override
protected void onRestart() {
super.onRestart();
mysong.getCurrentPosition();
mysong.start();
countDownTimer.start();
}
//When activity is destroyed then this will cancel the timer
#Override
protected void onStop() {
super.onStop();
countDownTimer.cancel();
}
//This will pause the time/
#Override
protected void onPause() {
super.onPause();
mysong.pause();
countDownTimer.cancel();
}
//On BackPressed
#Override
public void onBackPressed() {
Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
}
//This dialog is show to the user after he ans correct
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
//Since the dialog is show to user just pause the timer in background
onPause();
onRestart();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);
//Setting type faces
correctText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//INCORRECT//////////////////////////////////////////////////////////////
public void incorrectDialog() {
final Dialog incorrectDialog = new Dialog(MainGameActivity.this);
incorrectDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (incorrectDialog.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
incorrectDialog.getWindow().setBackgroundDrawable(colorDrawable);
}
incorrectDialog.setContentView(R.layout.dialog_incorrect);
incorrectDialog.setCancelable(false);
incorrectDialog.show();
//Since the dialog is show to user just pause the timer in background
onPause();
onRestart();
TextView IncorrectText = (TextView) incorrectDialog.findViewById(R.id.IncorrectText);
FButton buttonNext = (FButton) incorrectDialog.findViewById(R.id.dialogNext);
//Setting type faces
IncorrectText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
incorrectDialog.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//This method will make button color white again since our one button color was turned green
public void resetColor() {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}
//This method will disable all the option button
public void disableButton() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
//This method will all enable the option buttons
public void enableButton() {
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
}
public void pausedialog()
{
final Dialog pausedialog = new Dialog(MainGameActivity.this);
pausedialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (pausedialog.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
pausedialog.getWindow().setBackgroundDrawable(colorDrawable);
}
pausedialog.setContentView(R.layout.activity_dialog_pause);
pausedialog.setCancelable(false);
pausedialog.show();
//Since the dialog is show to user just pause the timer in background
onPause();
Button resume = (FButton) pausedialog.findViewById(R.id.resume);
Button menu = (FButton) pausedialog.findViewById(R.id.menu);
Button music = (FButton) pausedialog.findViewById(R.id.music);
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
pausedialog.dismiss();
onRestart();
}
});
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2 = new Intent(MainGameActivity.this,HomeScreen.class);
// mysong.release();
// finish();
startActivity(intent2);
finish();
}
});
}
}
EDIT: posted the full code. I tried understanding it again but I don't know what to do anymore this may be the only problem I have left other than inserting images (that's another problem for now I wanna finish this)
EDIT: I tried fixing the if statements like this:
if (button.getText().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
incorrectDialog();
coinValue--;
}
if (qid < list.size() - 1) {
disableButton();
} else
{
gameWon();
}
It works now, the last answer is now also registered if right or wrong BUT the dialog box flashes for a split second and automatically goes to the results screen.

how to change a button background and enable it after other buttons are pressed

How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.
I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).
int one = 0;
int two = 0;
int three = 0;
int four = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_price_estimate_question_one);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String phone_price = extras.getString("phone_price");
final String numonly = phone_price.replaceAll("[^0-9]", "");
final int phoneprice = Integer.parseInt(numonly);
final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
final Button nextstep = (Button)findViewById(R.id.next_step);
ques_one_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
one = 1;
ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_one_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
one = 1;
ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_one_no.setBackground(getDrawable(R.drawable.button_background));
ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_two_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
two = 1;
ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_two_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
two = 1;
ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_two_no.setBackground(getDrawable(R.drawable.button_background));
ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_three_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
three = 1;
ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_three_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
three = 1;
ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_three_no.setBackground(getDrawable(R.drawable.button_background));
ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_four_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
four = 1;
ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
ques_four_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
four = 1;
ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
ques_four_no.setBackground(getDrawable(R.drawable.button_background));
ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
}
});
}
}
Quesions
you can try "RadioGroup" and "RadioButton"
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup rb, int id){
if (id == R.id.ques_one_yes)
}
})
and in layout file
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/ques_one_yes"
android:layout_width="wrap_content"
android:BackGround="#drawable/rb_bg"
android:layout_height="wrap_content"/>
</RadioGroup>
and in drawable file rb_bg.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/button_background" android:state_checked="true"/>
<item android:drawable="#drawable/inactive_button_background"/>
</selector>
and the TextColor is other drawable file
The simplest implementation that comes to my mind is to check all of the int values you defined. You can do it in a helper method together with background and color changes
private void helperMethodName (Button buttonNo, Button buttonYes){
buttonNo.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
buttonNo.setBackground(getDrawable(R.drawable.button_background));
buttonYes.setTextColor(getApplication().getResources().getColor(R.color.black));
buttonYes.setBackground(getDrawable(R.drawable.inactive_button_background));
if (one != 0 && two != 0 && three != 0 && fore != 0) {
nextstep.setEnabled(true);
}
}
And then just call this method in your on clicks
public void onClick(View v) {
one = 1;
helperMethodName(ques_one_no, ques_one_yes);
}
Your are taking the initial values for all the options as 0 and making it 1 on OnClick.
Just give an if-else in your onCreate method like:
if(one = 1 && two = 1 && three = 1 && four = 1)
button.setEnable(true);
else
button.setEnable(false);
if all values are 1 then enable the button, else disable it.
In general if you want to achieve this implementation you can try the following ,
To enable/disable the next button:
fun enableNextButton(isEnable: Boolean) {
if(isEnable){
button_next?.alpha = 1.0f
button_next?.isEnabled = true
}else{
button_next?.alpha = 0.5f
button_next?.isEnabled = false
}
}
So call enableNextButton(true) if you want to enable the next button otherwise pass the false param to method. Also alpha sets the button blur which helps you to show the disable button view.

CountDownTimer not initiating in if statement

My problem is towards the bottom, I have a boolean, ongoing, which is false. It is supposed to become true with a button press, then initiate a countdown timer, but the timer is not initiated. The timer works placed elsewhere in the code. Sorry if it's a complete mess I'm new to this.
public int counter;
public boolean ongoing = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//0-59 number picker to represent seconds
final NumberPicker secPicker = (NumberPicker) findViewById(R.id.secPicker);
secPicker.setMaxValue(59);
Button btnStart = (Button) findViewById(R.id.btnStart);
Button btnSet = (Button) findViewById(R.id.btnSet);
Button btnPause = (Button) findViewById(R.id.btnPause);
final TextView label = (TextView) findViewById(R.id.txtCount);
//sets the time chosen to timer with button press btnSet
btnSet.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
counter = secPicker.getValue();
label.setText(String.valueOf(counter));
}
}
);
//starts timer from selected time, from number picker, with btnStart
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ongoing = true;
}
});
//disables, not worried about this yet
btnPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ongoing = false;
}
});
//supposed to turn on a timer with button press btnStart, but it does nothing this is my problem.
if (ongoing == true) {
//any replacement for 9999999, as an infinite value?
new CountDownTimer(999999999, 1000) {
public void onTick(long millisUntilFinished) {
label.setText(String.valueOf(counter));
counter--;
if (counter == -1) {
counter = 0;
cancel();
}
}
public void onFinish() {
}
}.start();
}
}
}
if (ongoing == true) // this will never work for you
You have putted above code inside oncreate before you click anything it will get call.
Either you should write below code inside btnStart click event or create one method and call from it.
//supposed to turn on a timer with button press btnStart, but it does nothing this is my problem.
if (ongoing == true) {
//any replacement for 9999999, as an infinite value?
new CountDownTimer(999999999, 1000) {
public void onTick(long millisUntilFinished) {
label.setText(String.valueOf(counter));
counter--;
if (counter == -1) {
counter = 0;
cancel();
}
}
public void onFinish() {
}
}.start();
}
Hope these help you.

Java global int

In an Android Studio app, I have following code:
boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
The idea is that when one of the 4 buttons is clicked, the int clicked is set to 1 and so the final button can only be clicked when it is 1.
But the code doesn't work like this; int clicked = 0; can't be accessed in other public void.
If one of the numbers 1,2,3,4 is clicked then final button can be clicked
The fix: Put public static boolean clicked = false;
under your public class YourClassName { line.
Reasoning: You need to learn how to scope your variables properly. You declared boolean clicked inside the onCreate() function, so the variable is gone after onCreate() is done running.
You should have put the clicked variable inside the class scope level, via public boolean clicked or public static boolean clicked so that even after the function returns, the value is saved.
I highly recommend a beginners java course or textbook before continuing on with your project(s).
Java does not have any concept of global variables. There is either an instance variable or a class variable. To define Global Variable you can make use of static Keyword.
static boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
Yes the variable int clicked = 0; has to be declared final before it is accessible in the other public void functions.
Try this declared a class say ClassClicked
public class ClassClicked {
int clicked;
public int getClicked() {
return clicked;
}
public void setClicked(int clicked) {
this.clicked = clicked;
}
}
Then changed
int clicked = 0;
to
final ClassClicked clicked = new ClassClicked();
clicked.setClicked(0);
And
clicked = 1;
to
clicked.setClicked(1);
Finally
clicked == 1
to
clicked.getClicked() == 1

Android button text color does not change

I'm working on a quiz app that has a question and to answer options. When the wrong answer (button) is clicked, the text color for that specific button turns red, as it should. However, when the right button is clicked, the text color for that particular button should turn green, wait a second, and then move on to the next question.
I have spent days trying to figure out why it doesn't work, googled for answers, but I still can't make it work.
I have tried using Handlers and Runnables, but it still doesn't work.
I have posted the full code for the activity below.
Please help!
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.question_layout);
Intent i = getIntent();
subject = (Subject) i.getSerializableExtra(Globals.SUBJECT);
questions = subject.getQuestions();
subjectId = subject.getSubjectId();
appPreferences = new AppPreferences();
livesLeft = 3;
index = 0;
maxQuestions = questions.size();
maxIndex = maxQuestions - 1;
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(maxQuestions);
answer1 = (Button) findViewById(R.id.buttonAnswer1);
answer2 = (Button) findViewById(R.id.buttonAnswer2);
setQuestionsAndAnswers(index);
TextView textView = (TextView) findViewById(R.id.textViewSubjectName);
textView.setText(subject.getSubjectName());
}
private void setQuestionsAndAnswers(int index)
{
currentQuestion = questions.get(index);
// Set question
TextView textViewQuestion = (TextView) findViewById(R.id.textViewQuestion);
textViewQuestion.setText(currentQuestion.getQuestion());
// Set correct answer
correctAnswer = currentQuestion.getCorrectAnswer();
sourceUrl = currentQuestion.getSourceUrl();
sourceText = currentQuestion.getSourceText();
// Set answer #1
initializeButton(answer1, currentQuestion.getAnswer1());
// Set answer #2
initializeButton(answer2, currentQuestion.getAnswer2());
// Set source
TextView textViewSource = (TextView) findViewById(R.id.textViewSource);
textViewSource.setText(sourceText);
textViewSource.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
textViewSource.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sourceUrl));
startActivity(browserIntent);
}
});
// Update progress
updateProgress(index);
}
private void initializeButton(Button button, String answer)
{
button.setText(answer);
button.setTextColor(Color.WHITE);
button.setBackgroundColor(Color.TRANSPARENT);
button.setEnabled(true);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
onClickContent(view);
}
});
}
private void onClickContent(View view)
{
Context context = getApplicationContext();
final Button button = (Button) view;
String answer = button.getText().toString();
if (answer.equalsIgnoreCase(correctAnswer))
{
button.setTextColor(Color.GREEN);
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (index == maxIndex)
{
appPreferences.editPreferences(context, Globals.PREFERENCE_KEY + subjectId, true);
playSound(Globals.SOUND_QUIZ_COMPLETED);
Toast toast = Toast.makeText(context, "Quiz \"" + subject.getSubjectName() + "\" finished",Toast.LENGTH_LONG);
toast.show();
finish();
} else
{
playSound(Globals.SOUND_CORRECT_ANSER);
// Go to next question
index++;
setQuestionsAndAnswers(index);
}
} else
{
if (livesLeft == 1)
{
playSound(Globals.SOUND_GAME_OVER);
Toast toast = Toast.makeText(context, "Game over", Toast.LENGTH_LONG);
toast.show();
finish();
} else
{
playSound(Globals.SOUND_WRONG_ANSWER);
button.setTextColor(Color.RED);
button.setEnabled(false);
livesLeft--;
TextView lives = (TextView) findViewById(R.id.textViewLives);
lives.setText("Lives: " + livesLeft);
}
}
}
private void updateProgress(int progress)
{
progressBar.setProgress(progress++);
}
private void playSound(int songId)
{
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), songId);
mp.start();
}
Firstly, Thread.sleep(1000); in your case runs on MAIN thread, causes MAIN thread to sleep, it's not suggested.
You may view.postDelayed to load next question after a delay,
private void onClickContent(View view)
{
Context context = getApplicationContext();
final Button button = (Button) view;
String answer = button.getText().toString();
if (answer.equalsIgnoreCase(correctAnswer))
{
button.setTextColor(Color.GREEN);
if (index == maxIndex)
{
appPreferences.editPreferences(context, Globals.PREFERENCE_KEY + subjectId, true);
playSound(Globals.SOUND_QUIZ_COMPLETED);
Toast toast = Toast.makeText(context, "Quiz \"" + subject.getSubjectName() + "\" finished",Toast.LENGTH_LONG);
toast.show();
finish();
} else
{
playSound(Globals.SOUND_CORRECT_ANSER);
// Go to next question
index++;
// Go to next question after 1000ms
view.postDelayed(new Runnable() {
public void run() {
setQuestionsAndAnswers(index);
}
}, 1000); //here delays 1000ms
}
}
...
}
This is what I use for the same purpose. It should work...
button.setTextColor(Color.GREEN);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Reset Color if you want to...
// Start new question here
}
}, 1000);

Categories

Resources