3

I have 2 variable in the main activity. i need to pass these variable values to the next activity.how can i do it?

   button.Click += delegate {
   var activity2 = new Intent (this, typeof(Activity2));
   activity2.PutExtra ("MyData", "Data from Activity1");
   StartActivity (activity2);
};
afra raheem
  • 63
  • 2
  • 5
  • What is type of those two variables? You can send any number of variables with Intent.putExtra() and get them in new activity onCreate() by Intent.getExtra() – Ajay Apr 30 '17 at 05:55
  • 5
    Possible duplicate of [How do I pass data between Activities in Android application?](http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Kevin Krumwiede Apr 30 '17 at 06:06

5 Answers5

5

create and object of intent and send your data throw putstring() or putExtra() methods

 Intent intent = new Intent(this, YourClass.class);
 intent.putString("key1", var1);// if its string type
 Intent.putExtra("key2", var2);// if its int type
 startActivity(intent);

on receiving side

Intent intent = getIntent();
String var1 = intent.getStringExtra("key1");
int i = var2.getIntExtra("key2", 0);
Abubakar
  • 374
  • 3
  • 16
1

Send data from MainActivity to Activity2 using:

Intent activity2 = new Intent(MainActivity.this, Activity2.class);
activity2.PutExtra("MyData", "Data from Activity1");
StartActivity(activity2);

Receive data in Activity2 using:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ..............
    ..................

    if( getIntent().getExtras() != null)
    {
        String myData = getIntent().getStringExtra("MyData");
    }

    ...............
    .....................
}
Ferdous Ahamed
  • 19,328
  • 5
  • 45
  • 54
1

FirstActivity

Intent intent = new Intent(this, Example.class); 
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
intent.putExtras(mBundle);
startActivity(intent);

SecondACtivity

String value = getIntent().getStringExtra(key);
0

You can also pass you values in bundle also

FirstActivity.java

Intent mIntent = new Intent(this, Example.class); 
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);
startActivity(mIntent )

SecondActivity.java

String value = getIntent().getExtras().getString(key)

Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

I think this will help you..

Upendra Shah
  • 1,681
  • 13
  • 21
-1

You can make this with a static variable.

MainActivity.java

public static String nameVariable= "Text";

SecondActivity.java

String textFromMainActivity = MainActivity.nameVariable;