Preventing Negative Numbers in TextView - android

I have a TextView that displays a number (in this case, the number is 10).
Now, i have a button so the user has to press that button 10 times in order for the number to hit 0, resulting in moving on to the next level. However,
I can keep hitting that button and it starts its way back into the negatives (-1, -2, etc.).
I tried to think of how I would prevent this but I'm at loss.. any ideas?
-----------------------------------EDIT-----------------------------------------
Okay, so here is my update (I got it to stop at 0):
public void onClick(View v) {
// TODO Auto-generated method stub
if (scr >= 1) {
scr = scr - 1;
TextView Score = (TextView) findViewById(R.id.Score);
Score.setText(String.valueOf(scr));
}
if (scr == 10)
{
aCounter.start();
}
if (scr == 1)
{
aCounter.cancel();
new AlertDialog.Builder(Tap_Game_Activity.this)
.setTitle("Congratulations!").setMessage("Go to Level 2?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface AlertDialog, int PositiveButton) {
setContentView(R.layout.activity_level02_activity);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface AlertDialog, int NegativeButton) {
}
}).show();
}
}});
}
(EDIT!): I fixed the AlertDialog by changing the 2 'Else If' statements to just 'If' statements. However, my timer still doesn't work :(, any help?

suppose number is the variable you are showing in the TextView, consider following code,
int number = 10;
if ( number > 0 )
{
yourTextView.setText ( String.valueOf ( number ) );
}
else
{
// do not set text
}

int i=10;
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
i--;
t1.setText(""+i);
int s1=(Integer.parseInt(t1.getText().toString()));
if(s1<=0)
{
b1.setEnabled(false);
}
}
});

Its all about Logic.
You have to check condition if ( YourCount < 0 ) then you have to disable that button or do not set value in textView as per condition.

This doesn't seem to have anything to do with Android, but more with Java specifically. You just want to make sure that your code doesn't allow you to get below 0.
Your code probably goes something like this:
if button is hit
then subtract 1 from x and setText to x
You want to just throw in something that also checks if number is greater than zero
Like:
If button is hit && x is greater than 0
then subtract 1 from x and setText to x
If that is the case, then I recommend that you step away from the Android platform, and do some Java tutorials and examples.

Related

Android: Button's onClick Method not processed linearly?

I'm learning Android app coding and thought it would be a nice idea to code TicTacToe. So I got me six buttons aligned linearly in one activity, which change their color when clicked on, depending on the player's turn (orange or blue). The onClickListener's onClick method goes as follows:
public void onClick(View v)
{
if(player == 1)
{
((Button)v).setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
}
else
{
((Button)v).setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
}
gameControl();
}
gameControl follows with the game basics: Check if a player won, if it is a draw or not etc.:
public void gameControl()
if(checkForWin())
{
playerWins(player);
}
else if(round == 9)
{
draw();
}
else
{
if(player == 1)
player = 2;
else
player = 1;
}
round++;
}
My problem is that if a player won, that is if the last button to win the game is clicked, the button's color won't change. Rather, the playerWins method (in gameControl) refreshes the "playfield" before the button's color changes. I've tried stuff like Handler.postDelayed and such because it seems like the entire onClick methods is run through before the button's color is addressed, but no success there. Why is the onClick method not processed linearly? Is there any way to refresh the activity or something? Thanks in advance ...
Thanks for the quick response, here are the requested methods:
private void playerWins(int player)
{
if(player == 1)
{
player1Points++;
Toast.makeText(this,"Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
round = 1;
}
if(player == 2)
{
player2Points++;
Toast.makeText(this,"Player 2 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
round = 1;
}
}
The resetBoard method:
private void resetBoard()
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
buttons[i][j].setBackgroundColor(Color.parseColor("#B0C4DE"));
}
}
}
Yes, it is happening to quickly i guess and that's why you are not seeing it. You have a some approaches:
1- Putting a refresh button somewhere and only refresh when it is clicked (This option would be good for example if users know it will be a draw and they want to start again before finishing). So with this option you will not reset before user see the update.
2- Showing an AlertDialog to say "Player X wins!" and when user press OK you reset the board. It would be something like
AlertDialog dialog = AlertDialog.Builder(context);
dialog.setTitle("Your title");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
resetBoard()
}
});
dialog.setCancellable(false);
dialog.show();
Also just check you can reduce some code refactoring, as you are repeating code. For example playerWins() could be
private void playerWins(int player){
if(player == 1)
{
player1Points++;
Toast.makeText(this,"Player 1 wins!", Toast.LENGTH_SHORT).show();
}
if(player == 2)
{
player2Points++;
Toast.makeText(this,"Player 2 wins!", Toast.LENGTH_SHORT).show();
}
updatePointsText();
resetBoard();
round = 1;
}

Score not incrementing when it's supposed to

What i'm trying to do is quite simple. I want to generate random numbers(rand1 & rand2) and have the user give the correct answer of the sum. There are 2 buttons and the correct answer could be on either one. I am using the randDecider variable to determine whether or not the correct answer should show up on the first or second button. The randDecider is either a 1 or 2.
The issue I am having is sometimes when I click on the correct answer, The score doesn't increment. And it turns out that sometimes when I press the wrong answer, the score increments. So i'm assuming it's a 50/50 chance the score will increment regardless if the answer is correct or not.
protected void setRandom(View v) {
//Assigning random values to ints
rand1 = r.nextInt(5) + 1;
rand2 = r.nextInt(5) + 1;
randDecider = r.nextInt(2)+1 ;
//The sum of the randoms
sum = rand1 + rand2;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
/*If the random deciding number is 1, set the correct answer
on the choice1 button*/
if (randDecider == 1){
choice1.setText(sum+"");
choice2.setText(sum+1+"");
//If the correct answer was chosen, increment the score and set the text
if(v.getId()==R.id.choice1){
score++;
scoreTV.setText(score+"");
}
}
/*If the random deciding number is 2, set the correct answer
to the choice2 button*/
if (randDecider == 2){
choice1.setText(sum+1+"");
choice2.setText(sum+"");
//If the correct answer was chosen, increment the score and set the text
if(v.getId()==R.id.choice2){
score++;
scoreTV.setText(score+"");
}
}
I'd suggest splitting the two distinct functions a) creating and presenting the problem to be solved and b) checking the response and then c) introducing a class variable to store the answer until another problem is presented (which would be after responding b) ).
So you could
a) add a line in the class
int correctanswer;
b) Add a method for setting the problem e.g. setProblem (called initially and then within c))
c) Add a method for checking the response e.g. setResponse which calls the setProblem method when the score has been adjusted. The setResponse method being called when either button is clicked.
d) add a call to initially invoke the setProblem.
e) set the 2 onclick listeners to call the setResponse method.
The following could be a resolution (based upon your question) :-
public class MainActivity extends AppCompatActivity {
int score, correctanswer;
TextView scoreTV, randTV1, randTV2;
Button choice1, choice2;
Random r = new Random(System.currentTimeMillis());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get UI components
scoreTV = (TextView) this.findViewById(R.id.score);
randTV1 = (TextView) this.findViewById(R.id.rand1);
randTV2 = (TextView) this.findViewById(R.id.rand2);
choice1 = (Button) this.findViewById(R.id.choice1);
choice2 = (Button) this.findViewById(R.id.choice2);
// Initialise
score = 0;
scoreTV.setText(Integer.toString(score));
setProblem();
// Button Listeners
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
}
});
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button) v);
}
});
}
// Set the problem
public void setProblem() {
//Assigning random values to ints
int rand1 = r.nextInt(5) + 1;
int rand2 = r.nextInt(5) + 1;
int randDecider = r.nextInt(2)+1 ;
//The sum of the randoms
int sum = rand1 + rand2;
correctanswer = sum;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
/*If the random deciding number is 1, set the correct answer
on the choice1 button*/
if (randDecider == 1){
choice1.setText(sum+"");
choice2.setText(sum+1+"");
} else {
choice2.setText(sum+"");
choice1.setText(sum+1+"");
}
}
// Check the user's response (called by onClick listeners)
public void checkResponse(Button v) {
if ((new Integer(v.getText().toString()) == correctanswer)) {
score++;
scoreTV.setText(score+"");
}
setProblem();
}
}
At the top of your method, you have several lines which generate the random numbers and the decider. These are correct.
Then, you show the random numbers and place the answers on the correct buttons, which is presumably also correct.
However, at the same time, you check whether the correct button is selected. This means you're checking against the last button the user pressed, not their answer.
One way to fix this is to save the sum and correct answer positions for at least one rotation. Change your setRandom method to generate the numbers and set them to the screen as they are now, but also to save the correct answer to an outside variable.
Then, in the button's onPressed method, check whether the pressed button is correct, increment the score, and call setRandom to put a new question on the screen.
The problem in your code stems from the fact that you check the answer right as you put the question on screen. Happy programming!

Passing a value via Button ( maybe hidden)

This code was working until last night, but now now. I'm wanting a value to be record that is linked to the buttons, I have used set and get tag but is only returning last value.
//create a layout
LinearLayout layout = (LinearLayout)findViewById(R.id.linearlayout);
// create a list of buttons
for(x=0; x<3; x++)
{
newBut = new Button(this);
newBut.setText("("TEXT");
newBut.setTextColor(Color.parseColor("#FFFFFF"));
newBut.setTag(x); //hide job id within the button.
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(newBut.getTag().toString());
System.out.println(newValue); //this just a test to display the value
}
});
layout.addView(newBut);
}
Is the error obvious - not to me.
It is returning the last value, because in all the created listeners you always reference the same button (last value of newBut variable), ignoring the actual click source view you have as the argument. Is should be:
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(v.getTag().toString());
System.out.println(newValue);
}
});

How to cycle over 3 types of values in array [android]

I want to know the algorithm to cycle through the sample array below in a order like color1 -> color3 -> color 2 when a button gets clicked each time.
int[] colorList = new int[]{color1, color2, color3};
Currently, Im trying to do it like the sample below but unable to do it.
If possible would you give me a helping hand ? I cannot find a solution to transition in a order I desire. I would love to hear from you!
void updateIndicators(int position) {
for (int i = 0; i < indicators.length; i++) {
indicators[i].setBackgroundResource(
i == position ? R.drawable.indicator_selected : R.drawable.indicator_unselected
);
}
}
Maybe something like this?
public int getNextPosition(int prevPosition){
int maxPosition=2;
return (prevPosition+maxPosition)%(maxPosition+1);
}
This returns 2 when input is 0
1 when input is 2
and 0 when input is 1
So colorList[0]->colorList[2]->colorList[1]
You can also add another function to return the color:
public int nextColor(int prevPosition){
return colorList[getNextPosition(prevPosition)];
}
First declare global variable on your activity class file like below :
int buttonclickcount=0;
In your clicklistener:
yourbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonclickcount++;
if(buttonclickcount%3==0)
{
//set color 1 from array
}
else if(buttonclickcount%3==1)
{
//set color 2 from array
}
else if(buttonclickcount%3==2)
{
//set color 3 from array
}
}
});

changing images on button click

I have 3 images in my app. The images are numbers. The maximum number displayed on all the 3 images will be 9. At first the image in the unit's place will be 1 and the rest images will be 0. On Clicking on the "next" button, the next number is being displayed i.e. 2. Proceeding in this way till the last number 9,then on the next click the unit's place becomes 0 and the ten's place becomes 1 and so on will proceed till 999. There is a previous button too which will reverse the condition of next button and will decrement the numbers by one digit. I am able to achieve the next button condition by using if else conditions but unable to do the same for previous button. please help.
int image1 = 2;
int image10 = 0;
int image100 = 0;
int max = 10;
final int [] images = {
R.drawable.num00,R.drawable.num_0, R.drawable.num1, R.drawable.num2, R.drawable.num3, R.drawable.num4,
R.drawable.num5, R.drawable.num6, R.drawable.num7, R.drawable.num8, R.drawable.num9
};
ImageButton next = (ImageButton)findViewById(R.id.imageButton1);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if((image1==max)&&(image10<max)) //for value with 9, 19... to increment
{
image1=1;
if (image10==0)
{
image10=2;
}
else
{
image10++;
}
img1.setImageResource(images[image1]);
img2.setImageResource(images[image10]);
}
else if((image1==max)&&(image10==max)&&(image100>=0)&&(image100<=10)) //for value with 9 in 1st block to increment
{
image1=1;
image10=1;
if (image100==0)
{
image100=2;
}
else
{
image100++;
}
img1.setImageResource(images[image1]);
img2.setImageResource(images[image10]);
img3.setImageResource(images[image100]);
}
else if (image100<=10) //for value below 9 in 1st block to increment
{
image1++;
img1.setImageResource(images[image1]);
}
}
});
Here, image1 is the position of image in the unit's place, image10 in the ten's place and image100 in the hundred's place.
The implementation can be optimized a lot.
Why cant you go for a simple number like below.
int number = 0;
for next button:
if(number <1000){
number++
updateImages()
}
for previous button:
if(number > 0){
number--
updateImages()
}
After doing the above line for those prev/next buttons, simply write a method like below.
updateImages(){
unitsPlace = number%10;
tensPlace = ((number/10)%10);
hundredsPlace = ((number/100)%10);
img1.setImageResource(images[hundredsPlace]);
img2.setImageResource(images[tensPlace]);
img3.setImageResource(images[unitsPlace]);
}
Thats it.

Categories

Resources