On clicking the button the app gets crashed displaying "Unfortunately, zm(app name) has stopped".
The IDE did not show any error.
I tried running this in 2 different devices but it didn't work.
Removing the final keyword shows an error.
ActivityMain.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView timer_text = (TextView) findViewById(R.id.text);
Button start_button = (Button) findViewById(R.id.button_start);
start_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final CountDownTimer timer = new CountDownTimer(30000,1000) { //setting time for 30 sec
@Override
public void onTick(long l) {
timer_text.setText((int) (l/1000)); //updating by reducing 1 second
}
@Override
public void onFinish() {
timer_text.setText(R.string.done); //string that shows completion
}
}.start();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="259dp"
android:layout_height="83dp"
android:text="Press the button to start"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.444" />
<Button
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:text="start"
app:layout_constraintTop_toBottomOf="@+id/text"
tools:layout_editor_absoluteX="161dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Your problem is a type mismatch.
You are doing:
timer_text.setText((int) (l / 1000));
But that mean that you are actually using the TextView.setText(int resId)
method, not the setText(String text)
method. Causing it to crash because there is no resource id with your calcul.
A simple solution would be:
timer_text.setText(String.valueOf(l / 1000));
Your code is a bit hard to read, you seems to have pasted multiple time our code.
You should not be using lower_snake_case as variable name, but lowerCamelCase instead.