Java if statement is being ignored - java

I'm making a simple app where the user clicks a button which changes a TextView to the corresponding string, but when my first if statement is fulfilled it does not go on to fulfill the following if statement which should be.
if (index == 0 && index > -1 && index < 5) {
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
index++;
text1.setText("1");
}
});
This is my first if statement, it sets the TextView to "1", and then should add to the integer "index", this turns the index's value to "1", which should end this statement because it no longer qualify, which will begin the following if statement.
if (index == 1 && index > -1 && index < 5) {
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
text2.setText("1");
index++;
}
});
Now because of the previous if statement setting the index's variable to "1" this if statement should begin and the previous end, but this is not the case, even though the variables no longer qualify, it doesn't stop and the next if statement does not begin. It's as though the if statement is being ignored.
UPDATE.
I fixed my problem and here's what I changed the code to:
one.setOnClickListener(new View.OnClickListener(){public void onClick(View v){
if(index == 0){
text1.setText("1");
index++;
}else if(index == 1){
text2.setText("1");
index++;
}else if(index == 2){
text3.setText("1");
index++;
}else if(index == 3){
text4.setText("1");
index++;
}
}});

From your if statement
if (index == 0 && index > -1 && index < 5)
only
if (index == 0)
is enough
same as Second one..
if (index == 1)

That's not how if statements work. When the condition becomes false control flow does not suddenly leave the block and jump to some other if-block with a true condition.

Your problem is that your index++ statement is inside the onClick callback. So this code is not executed until the button gets clicked. By that time, your second if statement will long be executed. In other words:
Your first if statement is true, this adds an onClick listener to the button. Your second statement is false, this does nothing. The user clicks on the button. Now only the code inside that first callback is executed: index is increased and the text is set to "1". That is all.
[EDIT this is probably what you want]
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if ( index == 0 ) {
index++;
text1.setText("1");
} else if (index == 1 ) {
text2.setText("1");
index++;
}
}
});

After index == 1 or index == 0 what is the relevance of the other conditions?

Another viable solution:
if ((index > -1) && (index < 5)) {
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
text2.setText(index.toString());
index++;
}
});
-Obviously this depends on the logic you require specifically, if you do require another occurrence when index == 0, you would have to alter this format:
if (index == 0) {
//Whatever you want to do here... eg:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
text2.setText("0");
index++;
}
});
}
else if ((index > -1) && (index < 5)) {
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
text2.setText(index.toString());
index++;
}
});

The reason that it doesn't work, is that the listener probably is added in "onLoad" method or in the constructor of the class.
Since your setOnClickListener is surrounded with a if statement, only the listener is only set if the statement is true. In your case the first statment is true, while the seccond statement is false.
This means that only the first listner is added, and everytime the button is clicked, the text1.setText("1") is called.
You should put your if statement inside your onClickListener, and not around the logic that sets the listener. So the following code:
if (index == 0 && index > -1 && index < 5) {
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
index++;
text1.setText("1");
}
});
should be
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (index == 0) {
index++;
// Do stuff
} else if(index == 1) {
index++;
// Do stuff
}
});
}
Every time the user hits the button 'one', the onClick is called.
Inside the onClick the statement is calculated, and the correct "Do stuff" is executed.

Related

Keeping track of digits before operator sign

For a calculator program, I keep track of all digits before an operator sign and limit their numbers to 12 with a counter, when an operator sign is selected, it resets the counter to zero. The problem with this is that if I delete the sign and continue editing those previous numbers, the count isn't in effect anymore because it has been reset to 0 after the operator sign. It there an alternative way to go about this?
Thanks in Advance!
private int numericCounter;
private boolean operatorAssigned;
private int cap = 12;
//if the number of digits is not 12, allow input
if (!(numericCounter >= cap)) {
textView.append(button.getText());
}
//if an operator "+" "-"...
//is rececived set numeric counter to 0
if (operatorAssigned) {
numericCounter = 0;
}
if (numericCounter == 0) {
operatorAssigned = false;
}
//Notification
if (numericCounter >= cap) {
Context context = getApplicationContext();
CharSequence text = "Maximum number of digits(12) reached";
int duration = Toast.LENGTH_SHORT;
//... show one Toast
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(context, text, duration);
mToast.show();
//show another Toast
if (mToast != null) mToast.cancel();
mToast = Toast.makeText(context, text, duration);
mToast.show();
}
//if maximum number of digits allowed
//not equal to 12
//increment numeric counter by 1
if (!(numericCounter >= cap)) {
numericCounter++;
}
//Handles the delete button
findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = textView.getText().toString();
if ((!text.isEmpty() && resultComputed == false)) {
String lastText = text.substring(0, text.length() - 1);
textView.setText(lastText);
lastNumeric = true;
//Checks if deleted text is a digit or an operator
if (lastText != "." || lastText != "+" || lastText != "-" || lastText != "/" || lastText != "/") {
numericCounter--;
}
} else if ((!text.isEmpty() && resultComputed == true)) {
textView.setText(txt);
resultComputed = false;
}
}
});
You could try a stack to keep a history of the counters. If you limit the stack to 2, you'll end up with the counter for the current number and the one for the previous number. Then, all you need to do is to manage the stack if you add/delete signs.
Just create a backup variable. something like
private int backUp = 0;
Then in your if(operatorAssigned) function,
do this:
backUp = numericCounter;
numbericCounter = 0;
This way, if and when you check for your deletion of operator, just assign the value of backUp to your numericCounter again.
This is just a very basic idea.

Button misfunction

When user click Next button, it suppose to show next record store in database, but when I run the app, user have to click previous button to view next entry and the Next button didn't perform any activity.
public void onClick(View v) {
int buttonId = v.getId();
if (buttonId == R.id.buttonViewPrevious)
if (currentBoothArrayIndex < boothArrayList.size() - 1) {
displayBoothInformation(--currentBoothArrayIndex);
} else if (buttonId == R.id.buttonViewNext)
if (currentBoothArrayIndex < boothArrayList.size() - 1) {
displayBoothInformation(++currentBoothArrayIndex);
}
}
your if else construct is wrong. Try this:
if (buttonId == R.id.buttonViewPrevious){
if (currentBoothArrayIndex < boothArrayList.size() - 1) {
displayBoothInformation(--currentBoothArrayIndex);
}
}else if (buttonId == R.id.buttonViewNext){
if (currentBoothArrayIndex < boothArrayList.size() - 1) {
displayBoothInformation(++currentBoothArrayIndex);
}
}

How to set text color of a text when a button is pressed in Java?

I have created programmatically, 5 radio groups with 4 radio buttons each. Every radio button represents an answer to a question. I want when someone press the button, if the correct answer is checked, to set the color of the that text in green. What am i trying to do, is to know in the second OnClickListener which radio button was checked, and if it is the correct one, to make the text green. So, with this code, when i press the button, nothing happens. If i remove the condition if (CorrectAnswer == 1) and i press the button, i get this error: Attempt to invoke virtual method 'void android.widget.RadioButton.setTextColor(int)' on a null object reference. Any ideas? Here is my code:
boolean isChecked;
RadioButton checkedRadioButton;
RadioGroup radioButtonGroup;
int CorrectAnswer;
radioGroup[i].addView(answer[j]);
answer[j].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkedRadioButton = ((RadioButton) v);
int CorrectAnswer = Integer.parseInt(checkedRadioButton.getTag().toString());
isChecked = true;
if (isChecked) {
if (checkedRadioButton.isChecked() & CorrectAnswer == 1) {
score++;
isChecked = false;
}
}
}
});
finishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < radioGroup.length; i++) {
int radioGroupId = radioGroup[i].getId();
radioButtonGroup = (RadioGroup) findViewById(radioGroupId);
int checkedRadioButtonId = radioButtonGroup.getCheckedRadioButtonId();
checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
if (CorrectAnswer == 1) {
checkedRadioButton.setTextColor(Color.GREEN);
}
for (int j = 0; j < answer.length; j++) {
radioGroup[i].getChildAt(j).setEnabled(false);
}
}
}
});
Thanks!
Do this to avoid calling methods on a null reference.
if (CorrectAnswer == 1 && checkedRadioButton != null)
EDIT:
Change the statement to this
if (checkedRadioButton != null && Integer.parseInt(checkedRadioButton.getTag().toString()) == 1)

this androied project give me a crash i am trying to make project that have a number from Edit text and get it in a text view times two

I want to get the value that I enter from edit text to a text view *2 but the app crashes.
public void sub (View v)
{
int val=Integer.parseInt( e1.getText().toString());
if(val <= 1)
{
t1.setText("you havn't ran any kilos");
}
else if(val > 1) {
t1.setText(val*2);
}
}
}
try this.
t1.setText(val*2 + "");
because val is Integer type and setText method's param is String type.
Try
public void sub (View v)
{
int val=Integer.parseInt( e1.getText().toString());
if(val <= 1)
{
t1.setText("you havn't ran any kilos");
}
else if(val > 1) {
t1.setText(String.valueOf(val*2));
}

Is there any method to store conditional statement in java?

I wanted to know if there is any method to store if else condition in java? What I mean is like having a variable to represent the condition. This is my original code
private OnClickListener click2 = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText("");
List<Integer> mClickedButtonIds = new ArrayList<Integer>();
int[] mDesiredOrder = new int[] { ans1.getId(), ans2.getId(), ans3.getId(),
ans4.getId(), ans5.getId() };
mClickedButtonIds.add(v.getId());
if (mClickedButtonIds.size() >= mDesiredOrder.length )
{
if (mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3]
&& mClickedButtonIds.get(4) == mDesiredOrder[4]
)
{
tv1.setText("Correct!");
}
else
{
tv1.setText("Try Again!");
}
mClickedButtonIds.clear();
}
}
};
I plan to change it to something like this
private OnClickListener click2 = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText("");
List<Integer> mClickedButtonIds = new ArrayList<Integer>();
int[] mDesiredOrder = new int[] { ans1.getId(), ans2.getId(), ans3.getId(),
ans4.getId(), ans5.getId(), ans6.getId() };
switch (main)
{
case 4 : Variable x = mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3];
case 5 : Variable x = mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3]
&& mClickedButtonIds.get(4) == mDesiredOrder[4];
case 6: Variable x = mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3]
&& mClickedButtonIds.get(4) == mDesiredOrder[4]
&& mClickedButtonIds.get(5) == mDesiredOrder[5];
}
mClickedButtonIds.add(v.getId());
if (mClickedButtonIds.size() >= mDesiredOrder.length )
{
if (x)
{
tv1.setText("Correct!");
}
else
{
tv1.setText("Try Again!");
}
mClickedButtonIds.clear();
}
}
};
The Variable x is something which I would like to ask. Is there any method to do so or is there any variable that can store if else condition. Cause the original code, it is fixed to 5 clicks. Now I want the number of required clicks to change according to how many clicks the user want.
Based on the code snippet, consider a loop:
boolean result = true;
for (int i = 0; i < main; ++i) {
result = result && mClickedButtonIds.get(i) == mDesiredOrder[i];
if (!result)
break; // short-circuit out from loop if false
}
// now you can use "result" to test whether the condition matched all "main" ids
if (result) {
// correct
} else {
// bzzt, try again
}
If I understand correctly, that you want x to be a condition that you may change programatically (but which conforms to some structure) then you can do this using an interface Question and classes which implement that interface
public interface Question {
boolean getResponse(String condition1, int condition2);
}
public class StringIsLongCondition implements Question{
public boolean getResponse(String condition1, int condition2) {
return condition1.length()>condition2;
}
}
public class StringIsShortCondition implements Question{
public boolean getResponse(String condition1, int condition2) {
return condition1.length()<condition2;
}
}
Then use like
Question x;
//some code that selects the question
x= new StringIsShortCondition();
if(x.getResponse(someString, someInt){
//do something
}

Categories

Resources