-5

I created in my Android project another activity. I execute it using this code(this is written in my main activity):

activity2 = new Intent(MainActivity.this, SecondaryActivity.class);
startActivity(activity2);

The problem is that I need to pass a value to the new activity. I've done it creating a public static value in the secondary activity. Can I do it in a different way?

EmLe49
  • 71
  • 10

3 Answers3

2

Use Intent extras :

Intent intent = new Intent(MainActivity.this, SecondaryActivity.class);
intent.putExtra("keyName","value");
startActivity(intent);

Then in SecondaryActivity's onCreate method, get value like this :

String data = getIntent().getExtras().getString("keyName");
Farhan
  • 1,000
  • 1
  • 11
  • 22
1

Try like this.

Intent activity2 = new Intent(MainActivity.this, SecondaryActivity.class);
activity2.putExtra("key", "value")
startActivity(activity2);

In SecondaryActivity.class

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //getData using key
    String value = getIntent().getStringExtras("key");
}
jack jay
  • 2,493
  • 1
  • 14
  • 27
Mohammad nabil
  • 1,010
  • 2
  • 12
  • 23
1

You can use Intent extras to pass value to your SecondaryActivity:

SEND:

// MainActivity.java

Intent intent = new Intent(MainActivity.this, SecondaryActivity.class);
intent.putExtra("KEY_VALUE", "Some value");
startActivity(intent);

RECEIVE:

// SecondaryActivity.java

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

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

    String value = "";
    if(getIntent().getExtras() != null)
        value = getIntent().getExtras().getString("KEY_VALUE");

    // Do something with value
}
Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61