0

Based on an earlier question. My button changes the value of the variable clicks. I was having trouble having visibletotals show at all times and be updated accurately. It was remaining static and stuck at 0. Example below of what my original code was doing. Only the value in the on click method was updating and it only showed upon click.

enter image description here

visibletotals.setText("Evolutions Points: " + clicks);  

I moved this line into my timer. I believe the visibletotals TextView is now updating correctly. However, it completely crashed my app giving me this error: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

How do I solve this error while keeping the TextView in my timer?

full code:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity {

    TextView points;
    TextView visibletotals;
    Button click;
    Button upgradebtn;
    TextView Leveltext;
    int clicks = 0;
    int clickcost = 10;
    int upgradelevel = 1;
    Timer myTimer = new Timer();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        click = (Button) findViewById(R.id.click);
        points = (TextView) findViewById(R.id.points);
        upgradebtn = (Button) findViewById(R.id.upgradebtn);
        Leveltext = (TextView) findViewById(R.id.leveltext);
        visibletotals = (TextView) findViewById(R.id.visibletotals);



        click.setEnabled(true);

        upgradebtn.setEnabled(true);

        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                clicks+= upgradelevel;
                visibletotals.setText("Evolutions Points: " + clicks);
            }
        }, 0, 1000);



        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clicks++;
                points.setText(getResources().getString(R.string.evol) + clicks);

            }


        });

        upgradebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (clicks >= clickcost) {

                    clicks -= clickcost;

                    upgradelevel += 1;

                    clickcost *= 2;
                    upgradebtn.setText(getResources().getString(R.string.Upgrade) +
                            clickcost +
                            getString(R.string.LevelText)
                            + upgradelevel);

                };
            }

        });


    }
}

0 Answers0