Passing variable "date" to another class via Intent on Android Studio, NULL OBJECT REFERENCE

pass by reference c++
pass by reference java
pass by value c++
pass by value-result
pass by value and pass by reference geeksforgeeks
pass by result
pass by name
pass by value vs pass by reference in c

quite new to android development here. I've been modifying a code and trying to get the date selected by a user on the calendar view to pass it to another class which would save to a database (an application that lets users create events for specific dates on calendar). My problem is when I pass it, the application crashes with a null object reference. I can't seem to find what is causing the null object reference and what needs to be changed. Any help would be appreciated.

CalendarActivity.java

package com.example.zaphk.studenthelperapplication3.calendar;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CalendarView;
import android.widget.Toast;

import com.example.zaphk.studenthelperapplication3.R;

public class CalendarActivity extends AppCompatActivity {
    public String date;
    private  static final String TAG = "CalendarActivity";
    private CalendarView mCalendarView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar_layout);
        mCalendarView = (CalendarView) findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView CalendarView, int year, int month, int dayOfMonth) {
                String date = year + "/" + month + "/"+ dayOfMonth ;
                Log.d(TAG, "onSelectedDayChange: yyyy/mm/dd:" + date);
                Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
                intent.putExtra("date",date);
                startActivity(intent);

                Toast.makeText(CalendarActivity.this,date,Toast.LENGTH_SHORT).show();

            }
        });
    }
}

CalendarEvent.java

package com.example.zaphk.studenthelperapplication3.calendar;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar;
import com.example.zaphk.studenthelperapplication3.calendar.database.CalendarAdapter;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar_DbHelper;
import com.example.zaphk.studenthelperapplication3.utils.MyDividerItemDecoration;
import com.example.zaphk.studenthelperapplication3.utils.RecyclerTouchListener;

import com.example.zaphk.studenthelperapplication3.R;


public class CalendarEvent extends AppCompatActivity {
    private CalendarAdapter mAdapter;
    private List<Calendar> notesList = new ArrayList<>();
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private TextView noNotesView;
    Intent intent = getIntent();
    public String date = intent.getStringExtra("date");


    private Calendar_DbHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);




        coordinatorLayout = findViewById(R.id.coordinator_layout);
        recyclerView = findViewById(R.id.recycler_view);
        noNotesView = findViewById(R.id.empty_notes_view);

        db = new Calendar_DbHelper(this);

        notesList.addAll(db.getAllNotes());

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNoteDialog(false, null, -1);
            }
        });

        mAdapter = new CalendarAdapter(this, notesList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
        recyclerView.setAdapter(mAdapter);

        toggleEmptyNotes();



        /**
         * On long press on RecyclerView item, open alert dialog
         * with options to choose
         * Edit and Delete
         * */
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
                recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {
            }

            @Override
            public void onLongClick(View view, int position) {
                showActionsDialog(position);
            }
        }));
    }



    /**
     * Inserting new note in db
     * and refreshing the list
     */
    private void createNote(String note) {

        // inserting note in db and getting
        // newly inserted note id
        long id = db.insertNote(note);

        // get the newly inserted note from db
        Calendar n = db.getNote(id);

        if (n != null) {
            // adding new note to array list at 0 position
            notesList.add(0, n);

            // refreshing the list
            mAdapter.notifyDataSetChanged();

            toggleEmptyNotes();
        }
    }

    /**
     * Updating note in db and updating
     * item in the list by its position
     */
    private void updateNote(String note, int position) {
        Calendar n = notesList.get(position);
        // updating note text
        n.setNote(note);

        // updating note in db
        db.updateNote(n);

        // refreshing the list
        notesList.set(position, n);
        mAdapter.notifyItemChanged(position);

        toggleEmptyNotes();
    }

    /**
     * Deleting note from SQLite and removing the
     * item from the list by its position
     */
    private void deleteNote(int position) {
        // deleting the note from db
        db.deleteNote(notesList.get(position));

        // removing the note from the list
        notesList.remove(position);
        mAdapter.notifyItemRemoved(position);

        toggleEmptyNotes();
    }

    /**
     * Opens dialog with Edit - Delete options
     * Edit - 0
     * Delete - 0
     */
    private void showActionsDialog(final int position) {
        CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose option");
        builder.setItems(colors, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    showNoteDialog(true, notesList.get(position), position);
                } else {
                    deleteNote(position);
                }
            }
        });
        builder.show();
    }


    /**
     * Shows alert dialog with EditText options to enter / edit
     * a note.
     * when shouldUpdate=true, it automatically displays old note and changes the
     * button text to UPDATE
     */
    private void showNoteDialog(final boolean shouldUpdate, final Calendar note, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null);

        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(CalendarEvent.this);
        alertDialogBuilderUserInput.setView(view);

        final EditText inputNote = view.findViewById(R.id.note);
        TextView dialogTitle = view.findViewById(R.id.dialog_title);
        dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_note_title) : getString(R.string.lbl_edit_note_title));

        if (shouldUpdate && note != null) {
            inputNote.setText(note.getNote());
        }
        alertDialogBuilderUserInput
                .setCancelable(false)
                .setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogBox, int id) {

                    }
                })
                .setNegativeButton("cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {
                                dialogBox.cancel();
                            }
                        });

        final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
        alertDialog.show();

        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Show toast message when no text is entered
                if (TextUtils.isEmpty(inputNote.getText().toString())) {
                    Toast.makeText(CalendarEvent.this, "Enter note!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    alertDialog.dismiss();
                }

                // check if user updating note
                if (shouldUpdate && note != null) {
                    // update note by it's id
                    updateNote(inputNote.getText().toString(), position);
                } else {
                    // create new note
                    createNote(inputNote.getText().toString());
                }
            }
        });
    }

    /**
     * Toggling list and empty notes view
     */
    private void toggleEmptyNotes() {
        // you can check notesList.size() > 0

        if (db.getNotesCount() > 0) {
            noNotesView.setVisibility(View.GONE);
        } else {
            noNotesView.setVisibility(View.VISIBLE);
        }
    }

    public String getDate(){
        return date;
    }
}

Logcat Error:

2019-10-06 21:49:33.346 26474-26474/com.example.zaphk.studenthelperapplication3 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.zaphk.studenthelperapplication3, PID: 26474
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.zaphk.studenthelperapplication3/com.example.zaphk.studenthelperapplication3.calendar.CalendarEvent}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2762)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2943)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1630)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6626)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
        at com.example.zaphk.studenthelperapplication3.calendar.CalendarEvent.<init>(CalendarEvent.java:41)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1196)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2752)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2943) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1630) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6626) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811) 

You should put

Intent intent = getIntent();
public String date = intent.getStringExtra("date");

inside the onCreate() method

As this stackoverflow answer the intent is set when creating the activity object. You can't access it before create the activity

Edit

You can add a getter like this

    Intent intent;
    public String date ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        intent =  = getIntent();
        date = intent.getStringExtra("date")
    }
    public String getDate(){
        return date;
    }

What's the difference between passing by reference vs. passing by , Passing such a reference falls under pass-by-value because a variable's value is technically the reference itself, not the referred object. However, the net effect on​  In Excel you can pass variables (an argument) between macros at run time. This allows you to have multiple modules and pass the value of a variable from macro A and send that value into macro B. The following is a short YouTube video that explains how to pass variables between macros. No Excel file is needed to sit through the presentation.


You're doing it on the wrong place. getIntent is not populated yet.

put getIntent().getStringExtra inside onCreate for example.

Variable Passing, Parameters passed by reference and by value. Passing by Reference Parameters are passed to IDL system and user-written procedures and functions by value  Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no effect on the original data stored in the argument variable.


You can't getIntent() before onCreate(), there's simply no Intent available at that point.

public String date = getIntent().getStringExtra("date");

write above line inside your onCreate().

UPDATE

Simply you have to decleare date variable at global scope and assign it within onCreate and then you can use it all over the class.

public String date ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        date =  getIntent().getStringExtra("date")
    }

Pass By Reference, Pass By Reference vs. Pass By Value. Reference Variables. A reference variable is a nickname, or alias, for some other variable; To delare a reference variable,  There are basically two ways of passing variables- Pass by Reference and Pass By Value. The former deals with the passing of reference or pointer to particular variable and the latter involves passing a copy of the variable to the method. C supports both ways of passing and the Pass By Reference is supported b means of Pointers.


Passing a Variable by Reference & Value in C Programming, In order to define a function that accepts the address of another variable, special variables called pointers need to be used in the function declaration and definition  Passing variables with data between pages using URL There are different ways by which values of variables can be passed between pages. One of the ways is to use the URL to pass the values or data. Here the biggest advantage is we can pass data to a different site even running at different servers.


Passing by Value vs. by Reference Visual Explanation, There are two possibilities how you could have passed the variable myAge to the function. The terms “pass by value” and “pass by reference” are  To pass a variable to one of the pass-through functions, you must build a dynamic query. Any data that includes quotes needs particular handling. For more information, see the "Using char and varchar Data" topic in SQL Server Books Online and see the following article in the Microsoft Knowledge Base:


Function pass by value vs. pass by reference, Critical to the discussion here is that this memory holds the formal parameter values and function local variables. By definition, pass by value means you are  It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = [].