我以前创建过许多视图,但是我不知道是什么导致了这个常见的异常。我寻找类似的问题,但由于这个例外是如此普遍,我似乎找不到与我相关的问题。
下面是代码:
public class DatesFragment extends Fragment {
CalendarView calendarView;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dates, container, false);
calendarView = view.findViewById(R.id.calendarId); //calendarView is null after this line. The view and the lay out are not.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentTime = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
calendarView.setDate(calendar.getTimeInMillis()); // this line causes the NullPointerException 下面是布局代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/parentId"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<CalendarView
android:id="@+id/calendarId"
android:layout_width="334dp"
android:layout_height="295dp"
android:layout_gravity="center"
android:layout_weight="1"
android:datePickerMode="calendar"
android:gravity="center"
android:scaleX="0.9"
android:scaleY="0.9"
android:spinnersShown="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>错误信息:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.CalendarView.setDate(long)‘
谢谢。
发布于 2021-01-02 11:26:38
正如评论中所回避的那样,日历并不在我试图发起它的片段中。它应该是在Alert Dialog中打开的,它有自己的布局,所以我将调用日历的代码移到Alert Dialog的代码中,问题就解决了。
https://stackoverflow.com/questions/65538135
复制相似问题