Why are my TextViews acting strangely? - android

I'm making a rather pointless android app that has two buttons, and two textviews.
It has a counter int set to 0.
The fist button named add, adds 1 to the counter, the second button named sub, subtracts one from the counter.
If the counter is greater than 1, the totalPlus textview is shown, with the current counter value.
If the coutner is equal to 0 or less, the totalMinus textview is shown, with the current counter value.
In both cases, the non-relevant textview is hidden.
The problem I'm having is that, say I'm on +5, the top counter will shown, and it will be seen incrementing when I press the button. But if I press the subtract button, the current textview hides, until I get to 0 or less in which the minusTextView displays. It works both ways.
[code]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
totalPlus = (TextView) findViewById(R.id.totalPlus);
totalMinus = (TextView) findViewById(R.id.totalMinus);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
if (counter > 1)
totalPlus.setVisibility(View.VISIBLE);
totalMinus.setVisibility(View.INVISIBLE);
totalPlus.setText("Your Total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
if (counter <0)
totalMinus.setVisibility(View.VISIBLE);
totalPlus.setVisibility(View.INVISIBLE);
totalMinus.setText("Your Total is " + counter);
}

Java ignores indentation levels. You need to use braces around all three statements which you want to be executed if the if statement passes.
if (counter <0) { // <-- this
totalMinus.setVisibility(View.VISIBLE);
totalPlus.setVisibility(View.INVISIBLE);
totalMinus.setText("Your Total is " + counter);
} // <-- and this
If you do not include these braces, Java only considers the first statement to be part of the if construct; the other two statements are outside that construct and will execute always.

Related

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!

how do u add multiple fixed int from four buttons to an array

edit.
I'm trying to make a game where there is 4 buttons each button has a set value.
buttone is 1 buttontwo is 2 and so on.
and on each click of the button it takes the value from what ever button is pressed and add it to an array, the number of buttons that you have to press is set by the intent from the main activity and the buttons that have to be press is set by the randomNums array.
eg.
if the randomNums give you 1,2,1,1,2.3,3,4.
green button must be pressed 3 times
blue button must be pressed 2 times
yellow button must be pressed once.
buttonOne must be pressed 3 times.
buttonTwo must be pressed 2 times.
buttonThree must be pressed 2 times.
buttonFour must be pressed once times.
I have the randomNums which gives you the up to 12 number from 1-4.
I have the buttons set up so that if the randomNums gives you 1,1,1,2,3,3.
ButtonOne will be green buttonTwo will be yellow and buttonThree will be blue
for 3 seconds then all the buttons turn grey.
but where I'm having trouble is how do u set a button to have a set value.
eg.
if I press buttonOne 3 times it will enter into an array like so 1,1,1.
so the question is how do set a fixed value to a button so that every time it is press it send a fix value to an array.
sry if I was not clear the 1st times around if u have any more question or if you need me to explain it again or want to see the code that I have to set the color of the button play let me know . thanks
hi I'm very new to android studio,
I have 4 buttons and I want each to have a fixed value.
ButtonOne =1;
ButtonTwo =2;
ButtonThree =3;
ButtonFour =4;
and when a button is pressed I want to add that fixed button value to an array.
what I have is sending an ++ number back and not sending a fixed value.
so my question is how do you send a multiple fixed int from four buttons OnClickListener to an array?
public int counterOne = 0;
final Button buttons[] = {
(Button) findViewById(R.id.ButtonOne),
(Button) findViewById(R.id.ButtonTwo),
(Button) findViewById(R.id.ButtonThree),
(Button) findViewById(R.id.ButtonFour)
};
buttons[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterOne = counterOne+1;
CheckSET.setText(""+counterOne);
}
});
final int pressed[] =new int [12];
end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stringlevel = ""+CheckSET.getText();
String b = "";
final int intLevel = Integer.parseInt(stringlevel);
for (int i = 0; i < 12;i++){
//b = ""+ b +""+ pressed[i];
//pressed[i] = pressed[i]+1;
//if(intLevel==1){
// pressed[i] = pressed[i]+1;
//}else if (intLevel ==2){
// pressed[i] = pressed[i]+2;
//}
pressed[0] = counterOne;
b = ""+ b +""+ pressed[i];
diff.setText(b);
}
}
});
the end button is to add all the button clicks to the array.
but if there is a better way then doing an end button to run the button array that would be great. could you do a for() and have all the buttons inside the for and each time they are pressed it adds it to the array?
I have a random array set up all ready that picks 12 numbers from 1-4 and does not let any number repeat more then 3 times.
private int[] pickNums() {
Random rand = new Random();
int randomNums[] = new int[12];
int one = 0;
int two = 0;
int three = 0;
int four = 0;
for (int i = 0; i < 12; i++) {
randomNums[i] = rand.nextInt(4)+1;
if (randomNums[i] == 1) {
one = one + 1;
if (one>3){
i=i-1;
}
} else if (randomNums[i] == 2) {
two = two + 1;
if (two>3){
i=i-1;
}
} else if (randomNums[i] == 3) {
three = three + 1;
if (three>3){
i=i-1;
}
} else if (randomNums[i] == 4) {
four = four + 1;
if (four>3){
i=i-1;
}
}
}
return randomNums;
}
my plan is to do a bubble sort on the randomNums and on the buttonPress array to see if the buttons that are pressed all ==.
but I'm having a lot of trouble with the buttonpress array
I am not sure what you asking but may be this will help you
(Instead of Array you should use list)
private List<Integer> pressedNums = new ArrayList<>();
Button button1,button2,button3,button4;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pressedNums.add(1)
}
});
similarly for button2,3,4 add 2,3,4
at last you can use loop
int total = 0;
for(Integer i : pressedNums){
total += i;
}
textField.setText(Integer.toString(total));

Android - How to calculate one edit text and divide another value?

I am a total beginner, I am wondering if anyone could help me out with the code. I am trying to make ideal daily water intake apps.
There will be only one edit text for user to input their weight and I want it to divide for example 0.024. Have button to calculate and then display the answer on screen.
public class WaterCalculate extends Activity {
//Declare textviews as fields, so they can be accessed throughout the activity.
EditText weightuser;
TextView tv4;
ImageButton calculate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.water_calculate);
//Bind the EditText views
weightuser = (EditText)findViewById(R.id.weight);
tv4 = (TextView)findViewById(R.id.res);
calculate = (ImageButton)findViewById(R.id.calc);
calculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calculate();
}
});
}
private void calculate() {
//get entered texts from the edittexts,and convert to integers.
Double value1 = Double.parseDouble(weightuser.getText().toString());
//do the calculation
Double calculatedValue = (value1/0.024);
//set the value to the textview, to display on screen.
tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));
}
}
When i run the apps the button to calculate its not working and it show the app has stopped. Appreciate for the help.
I thought the problem is in this line.
tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));
Give a try like this...
tv4.setText("You need "+Double.toString(calculatedValue)+"\nliters of water per day");
and also ensure that you catched the exceptions at necessary places like converting editText value into double.
Try the below code, am sure it will work, when you use click listener for button you should use View.Onclick
class WaterCalculate extends Activity {
// Declare textviews as fields, so they can be accessed throughout the
// activity.
EditText weightuser;
TextView tv4;
ImageButton calculate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.water_calculate);
// Bind the EditText views
weightuser = (EditText) findViewById(R.id.weight);
tv4 = (TextView) findViewById(R.id.res);
calculate = (ImageButton) findViewById(R.id.calc);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calculate();
}
});
}
private void calculate() {
// get entered texts from the edittexts,and convert to integers.
Double value1 = Double.parseDouble(weightuser.getText().toString());
// do the calculation
Double calculatedValue = (value1 / 0.024);
// set the value to the textview, to display on screen.
tv4.setText(String.valueOf("You need " + calculatedValue
+ "\nliters of water per day"));
}
}

Android loop on button click until argument not true

So I'm goofing around in Android Studio trying to set the button loop until counter<=3. However, if I click the button in the emulator it just skips to the statements after "if", why is that? Does the button do the things I specified in while in rapid succession instead of 1 time per click? How do I fix it?
Anyway here is the excerpt code:
button.setOnClickListener(new Button.OnClickListener() {
TextView myTextView;
int counter = 0;
public void onClick(View v) {
while(counter<=3){
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Button clicked");
counter++;
}
if(counter==4){
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("hello");}
}
Exactly as you thought, the while loop just executes until counter is no longer <= 3. Then if(counter==4) is true, and the if statement executes...
button.setOnClickListener(new Button.OnClickListener() {
TextView myTextView;
int counter = 0;
public void onClick(View v) {
if (counter == 4) {
myTextView = (TextView) findViewById(R.id.myTextView);
myTextView.setText("hello");
} else {
myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Button clicked");
counter++;
}
}
});
The while loop will execute over and over even though it is only called once (per click). That's why it's called a loop. You need to change it to an if statement - will execute once per click.
Also, I'd recommend declaring your TextView and counter globally at the top of your activity instead of inside your click listener. Then assign your TextView in onCreate()

Keep track of the scores (basketball scorekeeper)

i want to make an basketball scorekeeper app but i don't know how to add 2 or 3 points when i push the 2 points button or 3 points button?
the 1 point button works. this is the code of the button:
private int MyCount = 0;
final TextView countTextView1 = (TextView) findViewById(R.id.TextViewCountL);
final Button pointOne = (Button) findViewById(R.id.OnePointL);
pointOne.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MyCount++;
if (MyCount >-1)
countTextView1.setText("" + MyCount);
}
});
final Button pointTwo = (Button) findViewById(R.id.TwoPointL);
pointOne.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MyCount+=2;
if (MyCount >-1)
countTextView1.setText("" + MyCount);
}
});
and so on...
The line that increases MyCount by 1 is MyCount++. If you want to increase the score by 2 or 3 points, you need to increase MyCount by two or three by using the same line multiple times or MyCount += 2

Categories

Resources