javaandroid-studiochronometer

Cant seem to cast the Chronometer to an int


I am trying to convert the chronometer to seconds but cant seem to cast it as an int. As I need to put the seconds on a new activity.

Inconvertible types; cannot cast 'android.widget.Chronometer' to 'int'

 private Chronometer chronometer;
    private  boolean ChronometerRunnin;
    private  long pauseOffset;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // ButterKnife.bind(this);
        chronometer = findViewById(R.id.chronometerT);
        chronometer.setFormat("Timer: %s");
        buttonStats = findViewById(R.id.btRun);
        buttonStats.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openStatsPage();

            }
        });
    }

    public void openStatsPage(){
        Intent intent = new Intent(this, StatsPage.class);

        
         int elapsedMillis = (int) chronometer /1000;

        float timerdata = Integer.valueOf(chronometer.getText().toString());

        intent.putExtra("timedata",timerdata);

        startActivity(intent);
    }

Solution

  • You cannot cast a Chronometer type to int, you need to call the getBase() method.

    Try to change your openStatsPage method like this

    int elapsedTimeInSec = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000);
    
    Intent intent = new Intent(this, StatsPage.class);
    intent.putExtra("timedata", elapsedTimeInSec);
    
    startActivity(intent);