Benjamin Kinga Benjamin Kinga - 3 months ago 9
Android Question

Is there a way to pass a member function into a method by reference? [JAVA]

I'm trying to implement a counter in my app that increases every time the button is clicked. I then want to take the whatever the final value of the counter is and have it displayed in a dialog.

The problem is that when I call the variable, it returns the value that it initially had, not the one modified by the onClick method (This is weird to explain but I commented in my code to show what I mean).

final TextView points = (TextView) findViewById(R.id.points);
points.setText("Points = 0");

class ButtonClick implements View.OnClickListener {
int value = 0;
public void onClick(View v) {
value++;
changeLocation(theButton);
points.setText("Points = " + value); // This value increases
}

public int getValue() {
return value;
} // This returns 0.
}

final ButtonClick buttonClicked = new ButtonClick();
theButton.setOnClickListener(buttonClicked);

final int finalValue = buttonClicked.getValue(); // This still equals zero.

Answer

code is executed synchronously line by line

      // define and instantiate button listener 
1)    final ButtonClick buttonClicked = new ButtonClick();
      // attach listener to button
2)    theButton.setOnClickListener(buttonClicked);

            <------ here you still didn't executed onClick :) 

      // trying get value 
3)    final int finalValue = buttonClicked.getValue(); // This still equals zero.

when u hit line 3 you are getting value 0 because value is zero :)

try click (perform click -> do event or whatsoever ) then get value :)

to see if it works you need second async method example:

new Thread(new Runnable() {

        @Override
        public void run() {

            while(buttonClicked.getValue() ==0) {
                   // you didn't cliked

                     Thread.sleep(10000);
            }
       };
}).start();
Comments