开发者

CountDownTimer in Android

I am implementing countdown timer, but its not working 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));

        }
    }

}


It's this line causing the problem;

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

What you do, is set a resource id for textView1, while what you are looking for is something like;

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

Also line;

        iFallApp app1 = new iFallApp();

Is rather suspicious. Remove it just in case before you end up using it accidentally. You have your iFallApp created by Android framework already, and you can pass it using thisinstead if needed.


A heads up for any other developers following this as an example, but have abstracted their Timer into its own toplevel class. Passing a TextView into the CountDownTimer instance will result in a memory leak if you don't carefully clean up the references. This will be apparent after rotating the screen a half a dozen times, your app will crash with an OutOfMemoryError as mine did.

Add a method to your CountDownTimer like this, and call it whenever onDestroy()/onDestroyView() in the owning Activity/Fragment is called.

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


Typically you should be able to look at the adb logcat output to determine what's going wrong.

Off the top of my head I'd say that the textView1 variable is not being properly set and is null.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜