Hafeez Lawal Olabisi
Hafeez Lawal Olabisi

Reputation: 45

Passing data from two different intent in one activity to another activity

how can i pass different value from different intent inside another activity. i.e

Activity A:

ButtonA .onclick{

    intent.putExtra("name", screenname);

    intent.putExtra("email", description);

    intent.putExtra("pic", twitterImage);

    startActivity(intent);

}

ButtonB. onClick{

    intent.putExtra("anothervalue", json_object.toString())

}

Activity B:

  Intent intent = getIntent();

  String getValue = intent.getStringExtra("value from any of the button clicked")

Upvotes: 1

Views: 2753

Answers (5)

Tara
Tara

Reputation: 2648

@Mandeep answer is correct. But if you have more values coming from activity then here is the solution. Thanks to Mandeep

Intent i = getIntent();
String getValue1,getValue2,getValue3;

if(i.hasExtra("AFirstValue") && i.hasExtra("ASecondValue") && i.hasExtra("AThirdValue")){ 

getValue1 = i.getStringExtra("AFirstvalue");
getValue2 = i.getStringExtra("ASecondValue");
getValue3 = i.getStringExtra("AThirdValue");

}

if(i.hasExtra("anotherFirstvalue") && i.hasExtra("anotherSecondvalue") && i.hasExtra("anotherThirdvalue")){

getValue1 = i.getStringExtra("anotherFirstvalue");
getValue2 = i.getStringExtra("anotherSecondvalue");
getValue3 = i.getStringExtra("anotherThirdvalue");

}

Upvotes: 1

Mandeep
Mandeep

Reputation: 51

Intent intent = getIntent();
String getValue = null;

if(intent.hasExtra("firstvalue")){ 

getValue = intent.getStringExtra("firstvalue");

}

if(intent.hasExtra("anothervalue")){

 getValue = intent.getStringExtra("anothervalue");

}

Upvotes: 0

Hein
Hein

Reputation: 2683

While David Rauca answer is essentially correct, you will likely face NullPointerException.

getIntent().getStringExtra("firstvalue") will cause NPE if there is no value with name 'firstvalue'.

You should check whether or not value exist like this.

if(getIntent().hasExtra("firstvalue")) {
    String firstvalue = getIntent().getStringExtra("firstvalue");
}

Upvotes: 2

Rohit5k2
Rohit5k2

Reputation: 18112

Activity B code should be like this

Intent intent = getIntent();
String firstvalue = intent.getStringExtra("firstvalue");
String anothervalue = intent.getStringExtra("anothervalue");

if(firstvalue != null)
    // called from Button A click
else if(secondvalue != null)
    // called from Button B click

Upvotes: 0

David Rauca
David Rauca

Reputation: 1583

String getValue = intent.getStringExtra("firstvalue")  // in order to get the first value that was set when user clicked on buttonA

or

String getValue = intent.getStringExtra("anothervalue")  // in order to get the the value that was set when user clicked on buttonB

Upvotes: 0

Related Questions