I have a String
variable userBoat
that I’m trying to initialize inside an onClick
if statement. Unfortunately when I try to call it from another activity the variable is returning null
. I’ve tried initializing it as a global variable but then the other activity simply returns the value of the global variable – not the updated value from within the onClick
if statement. Thanks in advance for the help.
Here’s my code for the MainActivity
where I am declaring the variable:
public void onClick(View view) { if (mBarberi.isPressed()) { userBoat = "AJB"; myRef3.push().setValue("Date: " + date() + " || Boat: AJB"); startActivity(new Intent(getApplicationContext(), Thanks.class)); } }
And here is my code for the activity where I’m trying to receive the variable and assign it to a calendar API
public void onClick(View v) { MainActivity mainReference = new MainActivity(); if (mNone.isPressed()) { Intent intent = new Intent(Intent.ACTION_INSERT) .setData(CalendarContract.Events.CONTENT_URI) .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true) .putExtra(CalendarContract.Events.TITLE, mainReference.userBoat + " No O.T."); startActivity(intent); } }
Where mainReference.userBoat
refers to the variable in question.
Advertisement
Answer
You can just pass userBoat
as extra for the Intent
and then receive it in the Thanks
class.
Here is an example of the code in the MainActivity
:
Intent intent = new Intent(getApplicationContext(), Thanks.class); intent.putExtra(USER_BOAT_KEY, userBoat); startActivity(intent);
USER_BOAT_KEY
can be a static string somewhere in your code.
public static final String USER_BOAT_KEY = "user-boat_key"
And here is how to get it in the Thanks.class
:
Bundle extras = getIntent().getExtras(); if (extras.containsKey(USER_BOAT_KEY)) { String userBoat = extras.getString(USER_BOAT_KEY); // now you can use it here }