Android Studio - Passing variable with intent add extra, ends up with null

android intent
how to pass data from one activity to another in android using intent
android-intent putextra and getextra example
intent putextra object
kotlin intent putextra object
how can you pass several integer values to an activity which you start from your current activity?
intent putextra kotlin
which method of the intent class allows you to pass information to the target?

after fixing the null pointer exception of a previous question, (Not sure if posting a different question for the same code is okay, do let me know if it is not) I've come across a new problem. When I try passing the date variable from this first activity to another, it is always empty. I've also tried just setting a public getter or the variable and it is also empty. However, using a toast to check within the class shows that the variable does indeed contain the date. I am trying to pass the date class to be added into a database by the other classes in the application package. Any help would be much 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 static final String EXTRA_TEXT = "com.example.zaphk.studenthelperapplication3";
    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(Intent.EXTRA_TEXT,date);
                startActivity(intent);

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

            }
        });
    }
}

The class I am trying to receive it from : 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;


    private Calendar_DbHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        intent = getIntent();
        date = intent.getStringExtra(CalendarActivity.EXTRA_TEXT);

        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;
    }
}


You are using wrong key while passing data between activity.

Replace below line,

intent.putExtra(Intent.EXTRA_TEXT,date);

With this one,

intent.putExtra(CalendarActivity.EXTRA_TEXT,date);

How to pass variables to a new activity in Android (Android Studio , startActivity(i);. //step 3: add to activity you want to pulll variables from. Bundle extras = getIntent().getExtras();. if (extras != null) {. String someVariable = extras. We can start adding data into the Intent object, we use the method defined in the Intent class putExtra() or putExtras() to store certain data as a key value pair or Bundle data object. These key-value pairs are known as Extras in the sense we are talking about Intents.


You use the key of Intent.EXTRA_TEXT.

intent.putExtra(Intent.EXTRA_TEXT,date)

But you use the other key to receive. It's not the same key.

intent.getStringExtra(CalendarActivity.EXTRA_TEXT);

Intent.putextra – How to use Intents & Extras to pass data between , Intents in android offer this convenient way to pass data between activities using Extras. We can start adding data into the Intent object, we use the method defined in the or any type of object, we can serialize in one end get it at the other end. Android studio on Ubuntu – Complete installation guide. 0 Android Studio - Passing variable with intent add extra, ends up with null Oct 7 '19 0 Python Flask Application Context, how to expose app to other modules Apr 23 -1 RecyclerViewLayoutManager null object reference [duplicate] Oct 30 '19


As per I know (Not pretty sure)

Intent.EXTRA_TEXT

is used for implicit intents.

For explicit (i.e.Activity to Activity)

Do as below

Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra("DATE",date);
startActivity(intent);

To receive

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

Where "DATE" is String KEY.

Intent, Put together, the set of actions, data types, categories, and extra data defines a An activity to run when device is inserted into a digital (high end) dock. If set in an Intent passed to Context#startActivity , this flag will cause any Those apps should first prevent the call from being placed by setting resultData to null and  how to pass url from one activity to another activity, kindly please help me.. here by i'll add the snippet, when i run the program, activity is changing but page is blank.


I would say that CalendarActivity.EXTRA_TEXT is probably empty because you have not imported that class in to CalendarEvent.java

import com.example.zaphk.studenthelperapplication3.calendar.CalendarActivity; in CalendarEvent.java

and as other people have said the put and get on the Intent need to be the the same String value.

Build a flexible UI, we could end up with overlapping fragments. if (savedInstanceState != null) { return; } Intent, pass the Intent's extras to the fragment as arguments add<​HeadlinesFragment>(R.id.fragment_container, null, intent.extras) Developer guides · Design guides · API reference · Samples · Android Studio. Parcelable or Serializable, In both ways we have to add extra code and still get performance and memory hit. especially when we start passing more complex objects this is can become a serious performance hit. If we look in the Android Docs then there is another way of passing objects which is much faster.


Layouts and binding expressions, Intents and intent filters The user variable within data describes a property that may be used within chooses the left operand if it isn't null or the right if the former is null . When a plural takes multiple parameters, you must pass all parameters: Caution: Android Studio doesn't yet handle imports so the  The Intent object is the fundamental class that we use to pass data around in Android. It acts as a container of information to the system that we can manipulate. We’re going to see how we can transfer to an Activity and get a result back from that Activity as well.


Getting a result from an activity, The APIs provide default contracts for basic intent actions like taking a picture, requesting directly when declaring member variables for the returned ActivityResultLauncher instances. Pass in the mime type you'd like to allow the user to select Int, result: Intent?) : Uri? { if (resultCode != Activity.RESULT_OK) { return null } Android developers often face a predicament while passing object references to activities of whether to go with the Java Serialization method or opt for Android Parcelable. Passing primitive data types like string , integer , float , etc. through intents is quite easy in Android.


passing an array from one activity to another activity in android, public class profileview extends ListActivity { Bundle b=this.getIntent().getExtras(); String[] array=b.getStringArray(null); but it doesnt work..i put  A common appropriate example of adding Intent.EXTRA_CHOOSER_TARGETS is to surface relevant people or devices that your app provides. Excluding specific targets by component. You can exclude specific targets by providing Intent.EXTRA_EXCLUDE_COMPONENTS. This is to be used only to remove targets you have control over.