为什么我在android 4.0.3中得到TimePicker NullPointerException?

时间:2015-02-09 12:12:52

标签: java android android-dialogfragment android-timepicker

我有这个课程,它显示一个间隔为10分钟的时间选择器:

public class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        // Convert current minutes to tens
        // 55 = 50, 56 = 00
        int minute = c.get(Calendar.MINUTE) / 10;
        minute = (minute > 5) ? 0 : minute;

        final TimePickerDialog tpd = new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));

        tpd.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                int tpLayoutId = getResources().getIdentifier("timePickerLayout", "id", "android");

                ViewGroup tpLayout = (ViewGroup) tpd.findViewById(tpLayoutId);
                ViewGroup layout = (ViewGroup) tpLayout.getChildAt(0);

                // Customize minute NumberPicker
                NumberPicker minutePicker = (NumberPicker) layout.getChildAt(2);
                minutePicker.setDisplayedValues(new String[]{"00", "10", "20", "30", "40", "50"});
                minutePicker.setMinValue(0);
                minutePicker.setMaxValue(5);
            }
        });

        return tpd;

    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        minute = minute * 10;
        // Do something with the time chosen by the user
        final String selectedDate = String.valueOf(hourOfDay) + ":" + String.valueOf(minute);
        EditText selectedTimeTxt = (EditText) getActivity().findViewById(R.id.selectedTime);
        selectedTimeTxt.setText(selectedDate);
    }
}

代码完全适用于android Lollipop,但是当我在模拟器上运行它,或运行android 4.0.3的真实设备时,它会引发以下异常:

java.lang.NullPointerException关于此行:ViewGroup layout = (ViewGroup) tpLayout.getChildAt(0);

错误不仅仅是明确的,但我无法看到布局组件ID,因为API 15中不支持Device monitor中的屏幕捕获。

你能推我一把吗?为什么我收到此错误?我缺少的布局ID是什么?我很确定许多开发人员面临同样的问题。我知道我在这里错过了一小部分,但我无法发现它。

1 个答案:

答案 0 :(得分:2)

实际上问题在于:

int tpLayoutId = getResources().getIdentifier("timePickerLayout", "id", "android");

API-15 中没有名称为timePickerLayout的内部标识符。

因此tpLayoutId0,这使tpLayout等于null;并在null对象上调用方法抛出NullPointerException

建议:不要依赖于android的内部资源声明,因为这是他们被私有化的原因。