我正在关注Android开发的Big Nerd Ranch Guide第2版。我正在构建DatePickerFragment
来选择日期。该对话框通过按钮的onClick
启动。一切都已初始化。
DatePickerFragment.java
上课:
public class DatePickerFragment extends DialogFragment {
View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date, null);
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create();
}
}
我是从CrimeFragment.java
班级
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
...
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getDate().toString());
mDateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = new DatePickerFragment();
dialog.show(manager, DIALOG_DATE);
}
});
...
}
正如您所看到的,所有内容都已初始化(从我能看到的内容),但我收到此错误。
这是stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.view.LayoutInflater.from(LayoutInflater.java:232)
at myapp.onur.criminalintent.DatePickerFragment.<init>(DatePickerFragment.java:16)
at myapp.onur.criminalintent.CrimeFragment$2.onClick(CrimeFragment.java:77)
答案 0 :(得分:1)
将视图通胀移至onCreateDialog
,如下所示:
public class DatePickerFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date, null);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create();
}
}
问题是getActivity()
只会在调用onAttach()
后返回非空值。有关详细信息,请参阅the Activity/Fragment lifecycle。
答案 1 :(得分:-1)
添加:
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
v = inflater.from(getActivity()).inflate(R.layout.dialog_date, container, false);
return v;
}
所以你的代码将是:
View v;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
v = inflater.from(getActivity()).inflate(R.layout.dialog_date, container, false);
return v;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create();
}