java - 空检查后抛出空错误?

标签 java android if-statement nullpointerexception

有人可以解释为什么即使我正在检查 if 语句,scoreTextSwitcher 也会收到空错误吗?仅在启动 Activity 后引发错误 - 更改屏幕方向 - 再次更改屏幕方向 - 然后发生错误...

if(scoreTextSwitcher != null) {
       scoreTextSwitcher.setText(String.valueOf(a));
}

我尝试在下面的链接中寻找答案,但无法弄清楚它与我的代码有何关系。如果是这样,有人可以澄清一下吗?非常感谢。

<小时/>

这是整个方法(不确定在线程中是否重要)

 private void setScoreTextSwitcher(final int a){
    Thread setScore = new Thread() {
        public void run() {
            if(scoreTextSwitcher == null) {
                scoreTextSwitcher = (TextSwitcher) findViewById(R.id.score_text_switcher);

            }
            GameActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    if(scoreTextSwitcher != null) {
                        scoreTextSwitcher.setText(String.valueOf(a));
                    }
                }
            });
        }
    };
    setScore.start();
}
<小时/>

以下是错误消息:

08-27 11:02:10.226    2780-2780/com.major.color D/AndroidRuntime﹕ Shutting down VM
08-27 11:02:10.226    2780-2780/com.major.color W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-27 11:02:10.247    2780-2780/com.major.color E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at android.widget.TextSwitcher.setText(TextSwitcher.java:78)
            at com.major.color.GameActivity$6$1.run(GameActivity.java:600)
            at android.os.Handler.handleCallback(Handler.java:605)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4340)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
<小时/>

这是我程序的另一部分,也出现空指针错误。我相信这是同样的问题,因为它只在启动和来回更改屏幕方向时发生。希望第二个示例可以帮助缩小范围。

 private void startCountDownTimer(){
    isTimerOn = true;
    timerTextSwitcher = (TextSwitcher) findViewById(R.id.timer_text_switcher);
    timer = new CountDownTimer(timerCount, 1000) {
        public void onTick(long millisUntilFinished) {
            isTimerOn = true;
            timerCount = millisUntilFinished;

            if ( millisUntilFinished < 10001) {
                TextView TextSwTextView = (TextView) timerTextSwitcher.getChildAt(0);
                TextSwTextView.setTextColor(Color.RED);
                TextSwTextView.setText(String.valueOf(millisUntilFinished / 1000));
            }else
                if(timerTextSwitcher != null){
                    timerTextSwitcher.setText(String.valueOf(millisUntilFinished / 1000));}else {
                    timerTextSwitcher = (TextSwitcher) findViewById(R.id.timer_text_switcher);
                    timerTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

                        public View makeView() {
                            // Create a new TextView and set properties
                            TextView textView = new TextView(getApplicationContext());
                            textView.setLayoutParams(new TextSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            textView.setTextSize(17);
                            textView.setTextColor(Color.BLUE);

                            return textView;
                        }
                    });
                    timerTextSwitcher.setText(String.valueOf(millisUntilFinished / 1000));
                }
        }
   public void onFinish() {
            timerTextSwitcher.post(new Runnable() {
                @Override
                public void run() {
                    createToast("GAME OVER!");
                }
            });
            isTimerOn = false;

            saveScore();
            DialogFragment endDialog = new EndGameFragment();
            Dialog = endDialog;
            endgameVisible = true;
            endDialog.show(getSupportFragmentManager(), "EndGameDialogFragment");
        }
    };
    timer.start();
}
<小时/>

onCreate 方法的一部分显示了我如何为分数和 Activity 时间设置 TextSwitcher。

 @Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_game)
//more code...

 timerTextSwitcher = (TextSwitcher) findViewById(R.id.timer_text_switcher);
    timerTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            // Create a new TextView and set properties
            TextView textView = new TextView(getApplicationContext());
            textView.setLayoutParams(new TextSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            textView.setTextSize(17);
            textView.setTextColor(Color.BLUE);

            return textView;
        }
    });
    scoreTextSwitcher = (TextSwitcher) findViewById(R.id.score_text_switcher);
    scoreTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            // Create a new TextView and set properties
            TextView textView = new TextView(getApplicationContext());
            textView.setLayoutParams(new TextSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            textView.setTextSize(17);
            textView.setTextColor(Color.BLUE);
            textView.setText("0");
            return textView;
        }
    });

    // Declare the animations and initialize them
    Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
    Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

    // set the animation type to textSwitcher
    timerTextSwitcher.setInAnimation(in);
    timerTextSwitcher.setInAnimation(out);
    scoreTextSwitcher.setInAnimation(in);
    scoreTextSwitcher.setInAnimation(out);
}

最佳答案

以下几行导致了不良行为:

private void startCountDownTimer(){
    ...
    timerTextSwitcher = (TextSwitcher) findViewById(R.id.timer_text_switcher);

和:

private void setScoreTextSwitcher(final int a){
    ...
    scoreTextSwitcher = (TextSwitcher) findViewById(R.id.score_text_switcher);

这些对 findViewById() 的调用正在重新初始化切换器,导致它们丢失在 onCreate() 中获得的工厂和动画设置,并导致setText() 方法中的内部 NullPointerException。由于切换器似乎是在 Activity 范围内声明的,因此您只需删除这些行即可。

关于java - 空检查后抛出空错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526734/

相关文章:

java - "Zoom In/out "图像在 Android 中单击按钮?

if-statement - 为什么 Erlang 编译器说我的子句计算结果为假?

c - 如何制作这个程序?

javascript - JS Dice - 使用 if 条件将 Math.random 值分配给 html 图像

java - 利用 Hibernate 延迟加载?

Java 数据类型声明困惑

java - 我如何在struts2 if标签中使用请求参数

java - 如何将 currentMinute 和 currentHour 组合到一个文本字段中,以便它以正常时间格式显示 [ex 9 :30]

java - 如何使用 Selenium 网格使用远程计算机节点浏览器直接将文件下载到我的集线器计算机(我的项目代码工作区所在的位置)?

可水平滚动的安卓芯片