java – Variable that changes according to the pressed button

Question:

I have two different methods on two different buttons. the onE Method that adds 3 to the variable and the onM Method that subtracts -1 from the variable. The problem is that when I put this variable to appear in the textoid.setText(variavel) the app crashes. Would I have to convert this "int" variable to String , or am I wrong in the code structure? Follows him:

public class MainActivity extends AppCompatActivity {

private Button botaomid;
private Button botaoeid;
private TextView textoid;
public int variavel;


public void onM () {

    variavel = variavel - 1;
}

public void onE () {

    variavel = variavel + 3;
}


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

    botaoeid =(Button) findViewById(R.id.botaoeid);
    botaomid = (Button) findViewById(R.id.botaomid);
    textoid = (TextView)findViewById(R.id.textoid);


    textoid.setText(variavel);

    botaomid.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            onM();
        }
    });


    botaoeid.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        onE();

        }
    });
}
}

Answer:

First you have to initialize your variable, defining a value for it. Eg: 0 .

public int variavel = 0;

To avoid the error, just insert "" before the variable. See below:

textoid.setText(""+variavel);

Where

textoid.setText(String.valueOf(variavel));

By doing setText(int) you are referring to a resource from the XML file, not the value itself.

And finally, for your TextView to be changed when you click the button, you have to set the setText inside each button, like this:

botaomid.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            onM();
            textoid.setText(""+variavel);

        }
});
Scroll to Top