Ошибка при запуске активности. Unable to start activity ComponentInfo: java.lang.NullPointerException

Пытался создать активность (ввод времени, даты и названия какого-то занятия). Но получил ошибку. Ошибку именно в активности DateTime, как я понял. Так как я получаю ее не только, когда перехожу в эту активность по нажатию кнопки, но и когда открываю ее отдельно. Сама ошибка.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.DateTime}: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Calendar.getTimeInMillis()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Calendar.getTimeInMillis()' on a null object reference
at com.example.myapplication.DateTime.setInitialDateTime(DateTime.java:77)
at com.example.myapplication.DateTime.onCreate(DateTime.java:37)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
... 11 more

Разметка активности.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
    android:layout_height="match_parent">


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/backBtn"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="536dp"
        android:clickable="true"
        android:focusable="true"
        android:src="@drawable/ic_keyboard_arrow_left_black_24dp"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@android:drawable/ic_menu_add" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/enterBtn"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="536dp"
        android:clickable="true"
        android:focusable="true"
        android:src="@drawable/ic_keyboard_arrow_right_black_24dp"
        app:layout_constraintHorizontal_bias="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@android:drawable/ic_menu_add" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="-206dp"
        tools:layout_editor_absoluteY="0dp">

        <EditText
            android:id="@+id/activityName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="@string/title" />

        <TextView
            android:id="@+id/currentDateTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp" />

        <Button
            android:id="@+id/timeButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="setTime"
            android:text="@string/time" />

        <Button
            android:id="@+id/dateButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="setDate"
            android:text="@string/date" />

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Код активности.

public class DateTime extends AppCompatActivity {

    private String activityName;
    private Calendar dateAndTime;
    private TextView currentDateTime;
    private EditText editText;
    private FloatingActionButton backBtn;
    private FloatingActionButton enterBtn;

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        setContentView(R.layout.activity_date_time);
        currentDateTime = (TextView) findViewById(R.id.currentDateTime);
        editText = (EditText) findViewById(R.id.activityName);
        setInitialDateTime();
        dateAndTime = Calendar.getInstance();
        // получаю название занятия
        editText.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {}

            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                activityName = editText.getText().toString();;
            }
        });

    }

    // отображаем диалоговое окно для выбора даты
    public void setDate(View v) {
        new DatePickerDialog(DateTime.this, d,
                dateAndTime.get(Calendar.YEAR),
                dateAndTime.get(Calendar.MONTH),
                dateAndTime.get(Calendar.DAY_OF_MONTH))
                .show();
    }

    // отображаем диалоговое окно для выбора времени
    public void setTime(View v) {
        new TimePickerDialog(DateTime.this, t,
                dateAndTime.get(Calendar.HOUR_OF_DAY),
                dateAndTime.get(Calendar.MINUTE), true)
                .show();
    }

    // установка начальных даты и времени
    private void setInitialDateTime() {

        currentDateTime.setText(DateUtils.formatDateTime(this,
                dateAndTime.getTimeInMillis(),
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR
                        | DateUtils.FORMAT_SHOW_TIME));
    }

    // установка обработчика выбора времени
    TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            dateAndTime.set(Calendar.MINUTE, minute);
            setInitialDateTime();
        }
    };

    // установка обработчика выбора даты
    DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            dateAndTime.set(Calendar.YEAR, year);
            dateAndTime.set(Calendar.MONTH, monthOfYear);
            dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            setInitialDateTime();
        }
    };

}

P.s. Мой первый вопрос здесь, так что прошу, не судите строго)


Ответы (0 шт):