Search code examples
androidandroid-studiocountdowntimer

Application read minutes as seconds


I am new here so sorry if you will not understand something. So I am making countdown timer when I set value by + and - buttons and I would like to set this in "1min:10seconds" form but my app read it as 110 seconds. How to convert it?

public class MainActivity extends AppCompatActivity {
Button btn1, btn2, btn3;
TextView tv1;
int czasrundy=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1=findViewById(R.id.button1);
    btn2=findViewById(R.id.button6);
    btn3=findViewById(R.id.button7);
    tv1=findViewById(R.id.textView20);
    btn3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String czarundy=tv1.getText().toString();
            final long dłrundy = getTimeInLong(czarundy) * 1000;
            CountDownTimer countDownTimer=new CountDownTimer(dłrundy,1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                    tv1.setText ("" +millisUntilFinished/1000);
                }

                @Override
                public void onFinish() {
                }
            }.start();

        }
    });
}
public void odejmowanie1(View view) {
    if (czasrundy>=5){
        czasrundy=czasrundy-5;
        display2(czasrundy);
    }
}

private void display2(int czasrundy) {
    TextView displayInteger =(TextView)findViewById(R.id.textView20);
    String formatowanczas=String.format("%d:%02d", czasrundy/60, czasrundy %60);
    displayInteger.setText(formatowanczas);
}
public void dodawanie1(View view) {
    czasrundy=czasrundy+5;
    display2(czasrundy);
}
public long getTimeInLong(String input) {
    StringBuilder builder = new StringBuilder();
    String[] splittedString = input.split(":");
    builder.append(splittedString[0]);
    builder.append(splittedString[1]);
    return Long.parseLong(builder.toString());

}

}


Solution

  • I think that your problem is that when you parse your string you are concatenating "1" and "10" in the stringbuilder. You should parse do something like this

    public long getTimeInLong(String input) {
       StringBuilder builder = new StringBuilder();
       String[] splittedString = input.split(":");
       Long min = Long.parseLong(splittedString[0]) * 60;
       Long sec = Long.parseLong(splittedString[1]);
       
       return min + sec;
    }