How to use a variable in java within xml in Android Studio?-ThrowExceptions

Exception or error:

I am trying to make a score counter by using a TextView. I have set the text to “0” and want it to increase every time that a button is pressed. How can I accomplish this?

So far I am trying to call a variable from in the java of the activity but I do not know how to call the variable from within xml. Or change the value of the xml from java.

Any help is much appreciated and thanks in advance.

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="0"
        android:id="@+id/score"
        android:textSize="30sp"
        android:textColor="@color/black_overlay"
        android:layout_below="@+id/adView"
        android:layout_centerHorizontal="true" />

That is my xml and I currently have nothing written in the java portion other than setting up the onclick method.

public void buttonOnClick (View view) {
    Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_SHORT).show();
    //String yourString = this.getResources().getString(R.string.scoreCount);

    String mystring = getResources().getString(R.string.scoreCount);

}
How to solve:

Try like this

public void buttonOnClick (View view) {
   Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_SHORT).show();
   TextView score = (TextView) findViewById(R.id.score);
   score.setText("your_score");
}

###

You can try something like this:

int count = getResources().getInteger(R.integer.my_count);//why use string if you can use int
textView.setText(""+count++);//"" will cast count to string

###

You can’t really store a variable in XML, strictly speaking. However, you can just get the value in the field, increment it, and store the new value:

TextView view = (TextView) getViewById(R.id.score);
int score = Integer.parseInt(view.getText().toString());
view.setText(""+score++);

Throw this inside your onClick method.

Leave a Reply

Your email address will not be published. Required fields are marked *