2013年10月19日土曜日

TimePicker NullPointerException on ICS

TimePicker NullPointerException on ICS

下記のエラーが発生した。
E/AndroidRuntime(13629): FATAL EXCEPTION: main
E/AndroidRuntime(13629): java.lang.NullPointerException
E/AndroidRuntime(13629): at android.widget.TimePicker.updateInputState(TimePicker.java:580)
(以下省略)

このエラーの発生に再現性は無い。

質疑応答は下記のとおり。
TimePicker NullPointerException on ICS

TimePicker.javaの580行目近辺は次のようになっている。
565    private void More ...updateInputState() {
566        // Make sure that if the user changes the value and the IME is active
567        // for one of the inputs if this widget, the IME is closed. If the user
568        // changed the value via the IME and there is a next input the IME will
569        // be shown, otherwise the user chose another means of changing the
570        // value and having the IME up makes no sense.
571        InputMethodManager inputMethodManager = InputMethodManager.peekInstance();
572        if (inputMethodManager != null) {
573            if (inputMethodManager.isActive(mHourSpinnerInput)) {
574                mHourSpinnerInput.clearFocus();
575                inputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
576            } else if (inputMethodManager.isActive(mMinuteSpinnerInput)) {
577                mMinuteSpinnerInput.clearFocus();
578                inputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
579            } else if (inputMethodManager.isActive(mAmPmSpinnerInput)) {
580                mAmPmSpinnerInput.clearFocus();
581                inputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
582            }
583        }

このコードを読むと、午前午後スピナーがnullであったと想定される。
このため、TimePicker#setIs24HourView (Boolean is24HourView)を必ず使わねばならない、と言えるのではないだろうか。エラーが発生した私のコードでは、午前午後スピナーの使用の有無について明記していなかった。

見本は次のとおり。
        tp.setIs24HourView(false);
        tp.setCurrentHour(iHour);
        tp.setCurrentMinute(iMinute);
上記コードにおいて、setCurrentHourメソッドの引数に12-23の値を代入した場合、午前午後スピナーには午後と表示され、時間は0-11で表示される。