活动外的类中的变量

时间:2012-10-03 08:48:19

标签: java android class variables scope

我这样做了吗?我试图实现一个简单的倒数计时器,只是为了让我的脚踏实地。

我的计时器类没有嵌套在我的活动中,为了整洁,它们本身都在它自己的java文件中。这里:

public class McatTimer extends CountDownTimer {

    private TextView timer_tv;

    public McatTimer(long millisInFuture, long countDownInterval, TextView textview) {
        super(millisInFuture, countDownInterval);
        this.timer_tv = textview;
    }

    @Override   
    public void onFinish() {
        timer_tv.setText("DONE!");
    }

    @Override
    public void onTick(long millisUntilFinished) {
        timer_tv.setText("seconds remaining: " + millisUntilFinished / 1000);
    }

}

这里是logcat:

10-03 08:40:36.007: E/AndroidRuntime(2582): FATAL EXCEPTION: main
10-03 08:40:36.007: E/AndroidRuntime(2582): java.lang.NullPointerException
10-03 08:40:36.007: E/AndroidRuntime(2582):     at com.mangodeveloper.mcathomie.McatTimer.onTick(McatTimer.java:22)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:124)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at android.os.Looper.loop(Looper.java:123)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at android.app.ActivityThread.main(ActivityThread.java:3683)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at java.lang.reflect.Method.invokeNative(Native Method)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at java.lang.reflect.Method.invoke(Method.java:507)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-03 08:40:36.007: E/AndroidRuntime(2582):     at dalvik.system.NativeStart.main(Native Method)

我的活动在适当的地方有这些:

private McatTimer mcatTimer;

....

mcatTimer = new McatTimer(GAME_PREFERENCES_ROUNDTIME*1000, 1000, timerTv);
mcatTimer.start();

阅读这些记录还有一些技巧吗?对不起,我是自学。

1 个答案:

答案 0 :(得分:1)

看起来您的TextView对象为null。在调用

之前,请确保已初始化TextView
mcatTimer = new McatTimer(GAME_PREFERENCES_ROUNDTIME*1000, 1000, timerTv);

请致电,

timerTv=(TextView)findViewById(R.id.textview);