user3616949 user3616949 - 3 months ago 9
Android Question

Android use booleans correctly

I currently have a strange problem when it comes to using

booleans
in android. I first define the boolean, but when I use it, it does not return the correct value. Take the following code:

public class Prompt3 extends Activity {

boolean item1connect;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prompt3);

touchLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {


if (event.getAction() == MotionEvent.ACTION_DOWN){

if (Math.abs(startcoordinatesX - itemvar1x)<touchAllowance && Math.abs(startcoordinatesY - itemvar1y)<touchAllowance) {
item1connect = true;
}

if (item1connect = true) {
indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}
}

}

});

}


When I do the above,
indic1.setBackground
will
setBackground
, regardless of if
(Math.abs(startcoordinatesX - itemvar1x)<touchAllowance && Math.abs(startcoordinatesY - itemvar1y)<touchAllowance)
. However, when I try

if (Math.abs(startcoordinatesX - itemvar1x)<touchAllowance && Math.abs(startcoordinatesY - itemvar1y)<touchAllowance) {
indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard);
}


and bypass the
boolean
item1connect
altogether, the code works just fine. How can I fix this while including the
boolean
?

Thanks in advance

Answer

What you're doing is telling itemiconnect to set its value to true. Use the == operator to compare whether an item is true or false, or simply place itemiconnect into the parentheticals and it will check for you.

EDIT: Where your code says

if (item1connect = true) {
          indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}

you can change this to the comparator

if (item1connect == true) {
      indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}

or better yet just use the implied true functionality

if (item1connect) {
      indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}

Java allows you to simply call your boolean in an "if" statement as it represents a true or a false value.