1

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

B4listic
  • 21
  • 3
  • Please place your xml code also, thanks – Cyrille Con Morales Aug 28 '19 at 00:21
  • 1
    Per [your comment on the answer below](https://stackoverflow.com/questions/57683445/how-can-i-assign-functions-to-buttons-in-android-studio-with-out-having-the-vm-s#comment101831182_57683577), this would be a duplicate of [android.content.res.Resources$NotFoundException: String resource ID #0x0](https://stackoverflow.com/questions/20177003/android-content-res-resourcesnotfoundexception-string-resource-id-0x0). The accepted answer there explains why you needed to convert those to `String`s. – Mike M. Jun 21 '20 at 03:54

1 Answers1

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());
});

}
Cyrille Con Morales
  • 918
  • 1
  • 6
  • 21
  • i got it to work ; your code was : a) a bit broken , b) didnt achieve the goal i wanted. i am deeply sorry for wasting your time and feel like an idiot. all i did was convert score from an int to a string and and my origianal code worked as i wanted i to. It was your code that helped me realise this. sorry – B4listic Aug 28 '19 at 13:27
  • thats ok, its a good thing that you figure out what is wrong with your code, good luck – Cyrille Con Morales Aug 28 '19 at 13:30