0

My problem is:

I have 2 classes:

  • FirstActivity.java
  • SecondActivity.java

When I click on fab button on FirstActivity i want to pass a String variable to SecondActivity and go to SecondActivity. In SecondActivity, I will receive that String and Toast it up.

How can I do this ? Thanks you so much

Athira
  • 1,177
  • 3
  • 13
  • 35
Jason Momoa
  • 123
  • 8

2 Answers2

1

In your fab buttons onClick method

//creating and initializing an Intent object
Intent intent = new Intent(this, SecondActivity.class);

//attach the key value pair using putExtra to this intent
String user_name = "Jhon Doe";
intent.putExtra("USER_NAME", user_name);

//starting the activity
startActivity(intent);

In your SecondActivity onCreate method

//get the current intent
Intent intent = getIntent();

//get the attached extras from the intent
//we should use the same key as we used to attach the data.
String user_name = intent.getStringExtra("USER_NAME");

Source: https://zocada.com/using-intents-extras-pass-data-activities-android-beginners-guide/

Umskiptingur
  • 125
  • 1
  • 10
0

Put your this code in you fab button onClickListener

Intent mIntent = new Intent(mContext, SecondActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mIntent.putExtra("key", "Your value");
startActivity(mIntent);

And on SecondActivity.java receive like

String value = getIntent().getStringArrayExtra("key")

key is unique name for particular variable you can give as your requirement.

if you have pass variable then simple put your variable like

String str = "This is my meesage";
mIntent.putExtra("key", str);
Dinesh Shingadiya
  • 988
  • 1
  • 8
  • 23