繁体   English   中英

将数据从一个活动中的两个不同意图传递到另一个活动

[英]Passing data from two different intent in one activity to another 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())

}

活动B:

  Intent intent = getIntent();

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

虽然David Rauca回答基本上是正确的,但您可能会遇到NullPointerException

getIntent().getStringExtra("firstvalue")如果没有名称为'firstvalue'的值,将导致NPE。

您应该检查值是否存在。

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

@Mandeep的回答是正确的。 但是如果你有更多来自活动的价值,那么这就是解决方案。 感谢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");

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

要么

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

Activity B代码应该是这样的

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
Intent intent = getIntent();
String getValue = null;

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

getValue = intent.getStringExtra("firstvalue");

}

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

 getValue = intent.getStringExtra("anothervalue");

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM