Benjamin Kinga Benjamin Kinga - 1 year ago 76
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(;
points.setText("Points = 0");

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

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

final ButtonClick buttonClicked = new ButtonClick();

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

Answer Source

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() {

        public void run() {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download