CountDownTimer on Android

I use a countdown timer, but it does not work for me. Below is the code.

package FinalProj.com; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.os.CountDownTimer; public class iFallApp extends Activity{ public TextView textView1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //TextView textview = new TextView(this); //textview.setText("This is the iFall tab"); // setContentView() setContentView(R.layout.ifallapp); textView1=(TextView) findViewById(R.id.textView1); MyCount counter = new MyCount(5000,1000); counter.start(); } public class MyCount extends CountDownTimer{ public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } iFallApp app1 = new iFallApp(); @Override public void onFinish() { // TODO Auto-generated method stub textView1.setText("done"); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub textView1.setText((int) (millisUntilFinished/1000)); } } } 
+4
source share
3 answers

This line is causing the problem;

 textView1.setText((int) (millisUntilFinished/1000)); 

What you do is set the resource identifier for textView1, while what you are looking for is something like:

 textView1.setText(Long.toString(millisUntilFinished/1000)); 

Also a string;

  iFallApp app1 = new iFallApp(); 

Pretty suspicious. Remove it just in case before using it accidentally. You already have an iFallApp created by the Android platform, and you can pass it using this if necessary.

+10
source

And for other developers, they follow as an example, but they distracted their timer into their own class class. Passing a TextView to an instance of CountDownTimer will result in a memory leak if you do not clean the links thoroughly. This will be obvious after turning the screen half a dozen times, your application will crash using OutOfMemoryError, just like me.

Add a method to your CountDownTimer, like this one, and call it whenever onDestroy () / onDestroyView () is called in the activity / fragment that belongs to it.

 public void safeCancel() { this.textView1 = null; super.cancel(); } 
+1
source

Typically, you can look at the output of adb logcat to determine what is going wrong.

At the top of my head, I would say that the variable textView1 incorrectly set and is zero.

In addition, I would start the countdown timer in the onResume() function, not the onCreate() function.

0
source

All Articles