Android Studio Java: How to make a button break a while loop - java

I have question how to make button to break while loop. I don't have idea that this method exist at all.
For example i have while loop:
while(x==10000){
x++;
}
void onClick(view v){
// break the while loop
}
And i want to make a button, that when i clicked it i break the while loop and get x value. e.g x=9834. Ofc i want this button to most advanced function. I appreciate if you paste me code, how to make it. Thanks a lot for help!

Simply add another condition to break the while loop, that you control from your button :
boolean keepGoing = true;
while ((x==10000) && (keepGoing)) {
x++;
}
void onClick(view v){
keepGoing = false;
}

Related

Can && be used in if statements?

Im working on an app that converts a currency. I need it so that the user can enter an amount and then select one button which will have a specific material on it and then the user will click another button to convert it to another material. Eg copper converted into silver. But when I run the program for some reason when I click the calculate button nothing happens on the screen and no errors appear. Is it because I'm using && or something else I am very confused as to why it is not working. Here is my code:
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
btCalculate.setText(convert);
}
}
});
}
}
&& means and -- so both buttons have to be pressed at the same time for the if to evaluate to true? Not sure if this is what you intended to do.
When trying to figure out what is going wrong in your code you can use print statements or the debugging option in your IDE to step through your code line by line to see where the problem occurs.
I added a couple print statements to your code to show whether btCopper1 and btSilver2 are pressed and another print statement showing that the btCalculate() method will be called. If nothing prints to the console window at all then you aren't even reaching the onClick() method and something else went wrong before the portion of code that you posted.
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.out.println("btCopper1="+btCopper1.isPressed() + " btSilver2="+btSilver2.isPressed());
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
System.out.println("btCalculate is called");
btCalculate.setText(convert);
}
}
});

Disable Button on Activity, after user interacts with Buttons

Im having trouble disabling the Buttons for a particular question in my mQuestionsBank array. I created a mQuestionsAnswered boolean array with the size of the mQuestionsBank array to keep track of the questions that have been answered. Now, when the user interacts with either the "True" or "False" button, mQuestionsAnswered[mCurrentIndex] gets set to true, therefore disabling both of the buttons whether if they are right or wrong. Heres my code
Method to Enable Buttons image
Method to Check Answer image
True and False Button onClickListeners image
This is the code from your first picture:
private void buttonEnabler(){
if (...) {
...
} else
mTrueButton.setEnabled(true);
mFalseButton.setEnabled(true);
}
You're missing brackets on the else case. That means that this code "really" looks like this:
private void buttonEnabler(){
if (...) {
...
} else
mTrueButton.setEnabled(true);
}
mFalseButton.setEnabled(true);
}
In other words, mFalseButton will always be enabled, even when you don't want it to be. To fix it, add the brackets surrounding the else lines:
private void buttonEnabler(){
if (...) {
...
} else {
mTrueButton.setEnabled(true);
mFalseButton.setEnabled(true);
}
}
In your method buttonEnable, there's the if else error
Use else with {} brackets always, unless the statements to be executed is just one as illustrated below...
if (true)
say 'hello
else
be quiet
Or
if(true) {
say 'hello'
say 'how may I help you're
} else {
say statement 3
say statement 4
}

Java(Android) stuck in while loop

when I run my app it will continuously be stuck in a while loop. It should leave the while loop when a button is pressed, however even after pressing a button it continues to loop.
View.OnClickListener listener11 = new View.OnClickListener() {
#Override
public void onClick(View view) {
temp1 = button[0];
temp3 = button[0].getBackground();
state++;
}
};
while(state == 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
button[0].setOnClickListener(listener11);
}
variable:
state is an int temp1 is a button temp3 is a Drawable
the delay is there because I actually have 20 buttons and I have the setOnClickListeners for all the buttons inside that while loop so I think it causes it to crash without the delay. Another question would be is it possible to have the setOnClickListeners outside the while loop but still be able to check for button clicks inside the loop?
The problem is you are pressing the button while the thread is in a sleeping state causing the event to not be triggered and therefor the state to never change.
You should remove the while loop and just set all the listeners in a for loop:
for(int i = 0; i< button.length; i++) {
button[0].setTag(i);
button[0].setOnClickListener(listener11);
}
And then change your listener to be something like:
private boolean firstClick = true;
View.OnClickListener listener11 = new View.OnClickListener() {
#Override
public void onClick(View view) {
if(firstClick) {
firstClick = false;
temp1 = button[(int)view.getTag()];
} else {
temp2 = button[(int)view.getTag()];
}
}
};
I'm not sure exactly what the code is supposed to be doing because I have no idea of the context, but I think think you could remove the while loop altogether:
// initialize the listener
View.OnClickListener listener11 = new View.OnClickListener() {
#Override
public void onClick(View view) {
// add code that runs when button is clicked here
}
};
// now that we have the listener all set up we add it to the button, at which point it just keeps listening for you, no need to put the thread to sleep
button[0].setOnClickListener(listener11);
UPDATE:
So because you want to see if the second value matches the first value you could use a helper method:
private String firstValue = "";
public boolean isMatch(String mostRecentValue) {
boolean match = false;
if (firstValue.isEmpty()) {
firstValue = mostRecentValue;
} else {
match = firstValue.equals(mostRecentValue);
firstValue = "";
}
return match;
}
This method takes a value and if it is the first click the value is saved, if it is the second click it compares it with the first click and then resets the method. A boolean is returned false for no match, and true for a match. Call this method from within the onClick() method and pass in the buttons value. I've used String as an example value but you could use any object type.
I think you might be misunderstanding what setOnClickListener is doing. It's not handling the click, it is setting up the click handler. The line button[0].setOnClickListener(listener11); would be part of your activity initialisation and then not called again.
The reason you get stuck is because the main thread is busy in the while loop and isn't given an opportunity to process click events. Click events are handled on the main thread but only when it's not already busy doing something. In this case, it's forever busy in the while loop. For example, if the main thread was processing a method that would take 10 seconds to complete and you tap on a button 3 seconds into it, the button press wouldn't be handled for another 7 seconds. At which point, the previously set listener11 would be executed.
What you seem to be trying to achieve is already handled by the Looper. You need to be thinking in terms of event handling. So in other words, all your logic needs to go in listener11 or something similar.

Changing label text when button is clicked

I am trying to create a swing app that is a quiz. I need the jLabel to change on a button click but when I click the button, the app locks up. Can someone point me in the right direction?
My button click code is below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String[] questions = {"test0","test1","test2","test3","test4","test5","test6"};
String[] answers = {"","","","","","",""};
int i = 0;
do {
jLabel2.setText(questions[i]);
index.setText(String.valueOf(i));
if (txtAnswer.getText().toLowerCase().equals(answers[i].toLowerCase())) {
i++;
jLabel2.setText(questions[i]);
}
else {
add(lblWrong);
}
}
while(i < 7);
}
I am getting a warning that the evt parameter has not been used, could this be a problem?
Thank you
You don't want the do while loop. It's trapping you in the button press method as if you get an answer wrong you keep entering the else and can't leave it, stopping the app from working. Replace it with an if statement checking if i < 7.
In the else condition of your loop, you don't add 1 to i at all - therefore you can potentially end up in the situation where it's never incremented, thus it will be an infinite loop (locking your program up.)

Trouble with while to make a loop

cameraOn();
while (counter == 1){
if(counter == 0){
cameraOn();
counter += 1;
}else{
cameraOff();
counter -= 1;
}
}
The methods are:
private void cameraOff() {
// TODO Auto-generated method stub
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
}
private void cameraOn() {
// TODO Auto-generated method stub
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
and I have a button who have to break the loop and finish the activity:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (camera == null){
finish();
}else{
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
finish();
}
I'm a beginner and I don't understand how does the loop work, I tought with the counter I could do it, but it didn't work.
What I'm trying is to make the camera flash blink every second in a loop until I will press the button. please help me. Thanks
if (counter == 0) will never be true as your loop will exit in that case.
As others have said, entering a loop only when counter == 0 means it will never enter the inner loop requiring counter == 1, and never enter cameraOn().
Try this:
Clear out your onClick method and replace it with:
#Override public void onClick(View v) {
cameraOff();
/* or 'toggle();' if you prefer, see below */
}
(Since it appears to do exactly the same things.)
Comment out / delete that whole nested loop, and be sure to call cameraOn() or toggle() somewhere to get things started.
For setting up the toggle, you can add a static Boolean isFlashActive; (or otherwise detect the flash state, I haven't used that api yet)
..and add a function:
private toggle(){
if ( isFlashActive ) {
cameraOff();
} else {
cameraOn();
}
/* delay? */
}
For the toggle delay, you have a couple options:
First, you can call toggle() from another thread via a Runnable or one of the android options like AsyncTask while adding a wait() into the toggle function to provide the delay;
Second is my personal favorite, which is to setup an intent receiver then use setRepeating() with a PendingIntent.
The following part of your code will never be executed because you only enter the while block if counter == 1.
if(counter == 0){
cameraOn();
counter += 1;
So if you ever entered your while block while (counter == 1), you will always end up calling cameraOff() method. In other words your if statement will never be true and the else statement will be the one to be always executed.

Categories

Resources