how can i assign functions to buttons in android studio with out having the vm shut down

2

i am new to java and android studio ; i have set myself the goal of making a simple counter app in which one taps a button and a counter increases. Android studio shows no errors until i run t on my phone where it crashes as soon as i touch a button

i have tried to define the buttons as TextView tv; with no luck

public class MainActivity extends AppCompatActivity {
    private int score;//this lets me use it else where within the public class
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void startCounter(View v) {
        score = 0;
        TextView tv = findViewById(R.id.textView); //the text view defines it as tv
        tv.setText(score); //set the text of the label
    }
    public void buttonOnClick(View v) {
        score++; //adds 1 to score
        TextView tv = findViewById(R.id.textView); //the text view defines it as tv
        tv.setText(score); //set the text of the label



    }
}

i expect that the result is that the text view is updated to show the variable score but instead i get the error Invalid ID 0x00000000. and then D/AndroidRuntime: Shutting down VM

java
android-studio
asked on Stack Overflow Aug 27, 2019 by B4listic

1 Answer

1

I just replace your code so please copy and follow

int score=0;

public class MainActivity extends AppCompatActivity {
private int score;//this lets me use it else where within the public class
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

TextView tv = (TextView)findViewByID(R.id.tvID);
Button myButton = (Button)findViewByID(R.id.buttonID);
myButton.setOnClickListener(new View.OnClickListener{

    score++;
    tv.setText(score.toString());
});

}
answered on Stack Overflow Aug 28, 2019 by Cyrille Con Morales

User contributions licensed under CC BY-SA 3.0