I am making an app which is a guessing game between 1 and 100. The current version I am writing gives the player 7 tries to to find the correct guess. I have created a variable to display how many guesses the player has left, however once the player has guessed, the number of guesses decrements by more than one (usually two).
So basically the numberOfGuesses var. will decrement every time the checkGuess() method is run. I have tried placing the decrement in the event listener for when the player presses the button, but it's still decrementing by more than one. There is a setOnClick listener if the player clicks the mouse button too, and another for the enter button. When I use the button in the game, it decrements properly. When I use the ENTER button, it decrements by two. Is it running the button listener when I press ENTER?
I tried changing decrement from numberOfGuesses--; to --numberOfGuesses;
I tried assigning it as numberOfGuesses = numberOfGuesses - 1;
Here is the variables wiring to thew GUI, and the checkGuess() method
public class MainActivity extends AppCompatActivity {
private EditText txtGuess;
private Button btnGuess;
private TextView lblOutput;
private int theNumber;
private int numberOfTries = 7;
public void checkGuess() {
String guessText = txtGuess.getText().toString();//
String message = "";
try {
--numberOfTries;
int guess = Integer.parseInt(guessText);
if (guess > theNumber)
message = guess + " is too high. You have " +numberOfTries + " " + " tries left! ";
else if (guess < theNumber)
message = guess + " is too low. You have " +numberOfTries + " " + " tries left! ";
else{
message = guess +
" is correct! You finished with " +numberOfTries + " tries left. Let's play again!";
Toast.makeText(MainActivity.this, message,
Toast.LENGTH_LONG).show();
newGame();
}
} catch (Exception e) {
message = "Enter a whole number between 1 and 100.";
} finally {
lblOutput.setText(message);
txtGuess.requestFocus();
txtGuess.selectAll();
The newGame() method which generates a new random number
public void newGame(){
theNumber = (int)(Math.random() * 100 + 1);
numberOfTries = 7;
}
Here is the method which runs on execution of app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtGuess = (EditText) findViewById(R.id.txtGuess);
btnGuess = (Button) findViewById(R.id.btnGuess);
lblOutput = (TextView) findViewById(R.id.lblOutput);
newGame();
btnGuess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkGuess();
}
});
txtGuess.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
checkGuess();
return true;
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
I am expecting the numberOfGuesses to decrement from 7 to 6, but the actual output is decrementing from 7 to 5, when I use enter, it works as I want for the button click (or at least displaying as 7 to 5),
Pressing enter while the text field is selected would trigger the OnEditorActionListener (and so would any other change, as far as I can tell). Have you tried filtering that Listener by actionId to make sure it only goes off specifically for the enter key?
Related
I'm a complete newbie to Android Studio and have basic experience in Java. I tried to create an android app where the user has to input a number, once the button is clicked a random number is generated from 0-6, if the input number and the generated number is the same then the user gains 1 point. I've tried to implement a score counter but after 1 correct guess the score stays at 1 and never increases any further.
public class MainActivity extends AppCompatActivity {
String matchingnumbers = "Congratulations!";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void on_button_click(View view) {
TextView numberW = this.findViewById(R.id.textView);
EditText tvW = this.findViewById(R.id.editText);
TextView scoreW =this.findViewById(R.id.textView3);
Random r = new Random();
int dicenumber = r.nextInt(6);
numberW.setText(Integer.toString(dicenumber));
try {
int number = Integer.parseInt(numberW.getText().toString());
int tv = Integer.parseInt(tvW.getText().toString());
if(number==tv){
int score = 0;
score++;
Toast.makeText(getApplicationContext(), matchingnumbers, Toast.LENGTH_LONG).show();
scoreW.setText("Your score is = " + score);
}
}
catch (Exception ex) {
Log.e("Button Errors", ex.toString());
}
}
}
Don't declare score in the method, because it does not remain. Declare it in the class instead:
public class MainActivity extends AppCompatActivity {
String matchingnumbers = "Congratulations!";
//here
int score = 0;
// ...
}
The Code you have written is this ....
if(number==tv)
{
int score = 0;
score++;
Toast.makeText(getApplicationContext(), matchingnumbers, Toast.LENGTH_LONG).show();
scoreW.setText("Your score is = " + score);
}
Observe the statements in if condition. Inside the if you are creating score variable so each time the user gets the correct answer the score variable will be created and its incremented so you will get always 1 as output even you get the same combination so many times
So, understand the scope of that variable.
I started learning Android Development. I was building a basic addition game, where user has to click on button which shows the addition of two number. There are four Textviews. First one give the time limit for each question to answer. Second gives the question for the user. Third one gives the current score of the user and the last one gives whether the chosen open is correct or incorrect.
Everything is working except the First Button. Every time when the button is pressed the the counting takes very fast.
// When First button is pressed
public void onClickButton1(View view) {
correctIncorrect.setVisibility(View.VISIBLE);
if (Integer.parseInt(button1.getText().toString())==sum) {
correctIncorrect.setText("Correct");
correctUpdater();
}
else {
correctIncorrect.setText("Incorrect");
inCorrectUpdater();
}
}
//Similar to all the buttons
//To Update the score
public void correctUpdater() {
n++;
yourScore++;
score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
update();
}
public void inCorrectUpdater() {
n++;
score.setText(Integer.toString(yourScore) + "/" + Integer.toString(n));
update();
}
// To update the timer
//=======================================================================//
public void resetTimer() {
timer.setText(Integer.toString(temp)+"s");
if (temp == 0) {
inCorrectUpdater();
update();
}
else {
timeUpdater();
}
}
public void timeUpdater() {
Handler timeHandler = new Handler();
Runnable timeRunnable = new Runnable() {
#Override
public void run() {
temp--;
resetTimer();
}
};
timeHandler.postDelayed(timeRunnable,1000);
}
//=================================================================//
// Updater function
public void update() {
correctIncorrect.setVisibility(View.INVISIBLE);
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
question.setText(Integer.toString(a) + " + " + Integer.toString(b));
Log.i("info", "onCreate: a = " + a);
Log.i("info", "onCreate: b = " + b);
sum = a+b;
Log.i("info", "onCreate: sum = " + sum);
int whichButton = random.nextInt(4);
Log.i("info", "onCreate: random button is " + whichButton);
values.clear();
for (int i = 0; i< 4; i++) {
if (i == whichButton) {
values.add(sum);
}
else {
values.add(random.nextInt(50));
}
Log.i("info", "onCreate: value[" + i + "] = " + values.get(i));
}
button1.setText(Integer.toString(values.get(0)));
button2.setText(Integer.toString(values.get(1)));
button3.setText(Integer.toString(values.get(2)));
button4.setText(Integer.toString(values.get(3)));
temp = 10;
resetTimer();
}
Am I using the Handler incorrectly? What can I do?
Am I using the Handler incorrectly? What can I do?
A better way to do this is CountDownTimer, by using this you won't have to deal with Handler youself and you also have a provision to cancel a running CountDownTimer.
Everything is working except the First Button
Not really sure what can cause different behaviours on click of buttons with the same code in onClick(). But you can consider using the same onClickListener for all the 4 buttons, in this way :
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View button) {
correctIncorrect.setVisibility(View.VISIBLE);
if (Integer.parseInt(button.getText().toString())==sum) {
correctIncorrect.setText("Correct");
correctUpdater();
}
else {
correctIncorrect.setText("Incorrect");
inCorrectUpdater();
}
}
};
button1.setOnClickListener(myListener);
button2.setOnClickListener(myListener);
button3.setOnClickListener(myListener);
button4.setOnClickListener(myListener);
This will ensure that clicking any of the 4 buttons will have a same behavior (depending on the answer of course)
In case you get confused with the onTick() method on CountDownTimer, you can use modified CountDownTimer which will ensure that the timer doesn't miss any ticks.
I have a problem related click count. The problem is, I can't stop click when a number a click is given.
For example, I allow users to click a button 3 times, if clicks reached 3 times, then stop count, and do what I want.
This is my code I have used.
private int clickcount = 3;
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
// try to stop count but it can't, computer still counting
if (clickcount == 3)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
} // onClick
I think the trigger to do something might be when the click count is zero, not three:
if (clickcount == 0) {
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
It isn't clear whether the above if statement belongs nested inside the outer if, or if it should be at the method level of onClick().
Note: We could have written if (clickCount <= 0), but there may not be a need to do this (nor may it be desirable), since after you have changed the visibility of those elements to GONE once, you don't need to do it again.
Make this Change,
private int clickcount = 3;
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
// try to stop count but it can't
if (clickcount <=0) <== make this change
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
}
try this
private int clickcount = 3;
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
// try to stop count but it can't, computer still counting
if (clickcount == 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
} // onClick
private int clickcount = 0;
#Override
public void onClick(View v) {
// Do button click handling here
if ( clickcount<3 ) {
clickcount++;
tombolbaca.setText("Baca " + clickcount + "x");
}
//Count stops here..
else
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
}
}
I am creating an app in which coins/points increases on watching reward video ads and those coins/points should be saved to firebase.
For example: every time on button click the coins value increases to 10 points. Now when I completely destroy the app and open it again, the points value should show the same, not zero
Here is my code till now without database implementation
private TextView mText;
private int coinCount;
mText = (TextView) findViewById(R.id.money);
coinCount = 0;
mText.setText(" " + coinCount);
Button button = (Button) findViewById(R.id.buynow);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (coinCount <= 29) {
//if(coinCount <30) {
new MaterialStyledDialog.Builder(MainActivity.this)
.setTitle("Not Enough Coins")
.setDescription("Watch the Ad To Get 10 coins")
.setIcon(R.drawable.ic_money)
.withIconAnimation(true)
.withDialogAnimation(true)
.withDarkerOverlay(true)
.setHeaderColor(R.color.color)
.setPositiveText("Get some coins")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
mRewardedVideoAd.show();
}
})
.show();
} else {
coinCount = coinCount - 30;
mText.setText(String.valueOf(coinCount));
}
}
});
My queston is how to Save The Coin value to DATABASE and retrieve it ?
Simple problem to fix (I hope)...can't figure it out myself though.
I need one radio button to be un-checked or un-selected when the other is checked/selected.
Here is my code. Right now the app works fine but when the user goes to change the selection the first button doesn't clear:
Button convert = (Button) findViewById(R.id.btnConvert);
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
weightEntered=Double.parseDouble(weight.getText().toString());
DecimalFormat tenth = new DecimalFormat("#.#");
if (lbToKilo.isChecked()) {
if (weightEntered <= 500) {
convertedWeight = weightEntered / conversionRate;
result.setText(tenth.format(convertedWeight) + " kilograms");
} else {
Toast.makeText(getApplicationContext(), "Pounds must be less than 500.", Toast.LENGTH_LONG).show();
}
}
if (kiloToLb.isChecked()) {
if (weightEntered <= 225) {
convertedWeight = weightEntered * conversionRate;
result.setText(tenth.format(convertedWeight) + " pounds");
} else {
Toast.makeText(getApplicationContext(), "Kilos must be less than 225.", Toast.LENGTH_LONG).show();
}
}
}
});
You simply need to group your RadioButtons in a RadioGroup.
That's all you need to get some mutually exclusive RadioButtons.
For your reference: http://developer.android.com/guide/topics/ui/controls/radiobutton.html